Compare commits

...
Author SHA1 Message Date
John Colvin 038159c00f GridSettingsVM was changing background to black when 'show_background' was false 2019-12-09 14:56:13 -06:00
John Colvin ad14430d12 MDDaemon - check that synthetic metadata.HasStrategy before adding to map 2019-12-09 14:56:12 -06:00
John Colvin 304bf96513 fix flickering pnl hyperlink hover background 2019-12-09 14:56:12 -06:00
John Colvin a5e7f46ce0 fix flickering mview hyperlink hover background 2019-12-09 14:56:12 -06:00
John Colvin ec60b98dce PNLView - HyperlinkCell mouse hover animation 2019-12-09 14:56:12 -06:00
John Colvin 3297154639 PNLView - set Hyperlink/TextCell 'SnapToDevicePixels' to true 2019-12-09 14:56:12 -06:00
John Colvin fea2eeaab0 PNLView - get rid of magic const row height 2019-12-09 14:56:12 -06:00
John Colvin 8176f4bd28 PNLView.xaml - factor out common TextCell props into base style 2019-12-09 14:56:12 -06:00
John Colvin 838ecc8cf2 PNLView.xaml - factor out common HyperlinkCell props into base style 2019-12-09 14:56:12 -06:00
John Colvin 1aa0a73260 set HyperlinkCell 'HyperlinkClickMode' default to 'Anywhere' 2019-12-09 14:56:12 -06:00
John Colvin fd6dd9f071 remove HyperlinkColumn props 'padding' and 'HyperlinkClickMode' (callers should set them through the ElementStyle prop) 2019-12-09 14:56:12 -06:00
John Colvin de22fe5e33 add 'AffectsRender' flag to Hyperlink/TextCell HorizontalContentAlignment dps 2019-12-09 14:56:12 -06:00
John Colvin d2509def2a fix Hyperlink/TextCell padding (actually use it) 2019-12-09 14:56:12 -06:00
John Colvin 475652f232 after opening, mview remembers subsequent security criteria changes in workspace 2019-12-09 14:56:12 -06:00
John Colvin 7583dcd386 mview synth fills popup only shows fills of synth root algos 2019-12-09 14:56:12 -06:00
John Colvin 896b4bc318 mview mini ob only shows working orders 2019-12-09 14:56:12 -06:00
John Colvin 664c88542b mview mini orderbook only shows exchange orders for outrights, spreader orders for synths 2019-12-09 14:56:12 -06:00
John Colvin f7a1b55385 fix mview sorting (use new ColumnSortManager) 2019-12-09 14:56:12 -06:00
John Colvin acb7a366f8 MarketViewVM - move local methods (in constructor) to bottom 2019-12-09 14:56:12 -06:00
John Colvin 37fe134f86 mview toolbar menu items open regular windows instead of minis (for now) 2019-12-09 14:56:12 -06:00
John Colvin e038431a6f mview fills/orderbook toolbar menu items open the new popups 2019-12-09 14:56:12 -06:00
John Colvin 3d0b40c101 DIYGridRowsPresenter initialization in Loaded callback is idempotent (Loaded event not always followed by Unloaded event) 2019-12-09 14:56:12 -06:00
John Colvin 0f42d113e4 mview popups use AutoHideScrollBar to prevent scrollbars from covering data 2019-12-09 14:56:12 -06:00
John Colvin 8f57b22b58 mview 'Position' column shows day position (uses position service) 2019-12-09 14:56:11 -06:00
John Colvin c8be6fb6ca tweak HyperlinkCell mouse-capture/mouse-over-click-area logic 2019-12-09 14:56:11 -06:00
John Colvin 5e5db254de clean up DIYGrid TextColumn (mimic recent changes in HyperlinkColumn) 2019-12-09 14:56:11 -06:00
John Colvin 9919ca8737 fix TextCell alignment issues 2019-12-09 14:56:11 -06:00
John Colvin 2f59900a69 SP-257 mview popups for working orders & day fills 2019-12-09 14:56:11 -06:00
John Colvin 7875b939e6 spruce up hamburger menu 2019-12-09 14:56:11 -06:00
John Colvin 2e61db0e47 add 'Freeze' prop to BrushExtension 2019-12-09 14:56:11 -06:00
John Colvin 89d4636b90 add ITimeAndSalesGridSettingsMigrationRule 2019-12-09 14:56:11 -06:00
John Colvin bf7f25c1f5 DIYGridCellHoverAdorner 2019-12-09 14:56:11 -06:00
John Colvin dccb9e2b25 refactor DIYGrid.SelectionHighlight to be Color instead of Brush (also fixes drag rect adorner bug, where the color wouldn't respond to settings changes) 2019-12-09 14:56:09 -06:00
John Colvin a1d8f966d0 HighPerformanceRow does not depend on TColumn 2019-12-09 14:55:21 -06:00
John Colvin 69e439f029 fix typo in ColumnGeometry (was assigning 'left' to 'unclicpped_left') 2019-12-09 14:55:21 -06:00
John Colvin 79bf995e7b add 'HyperlinkClickMode' to HyperlinkCell to support cmd on click anywhere 2019-12-09 14:55:20 -06:00
John Colvin 2473e27b83 fix HyperlinkCell HorizontalAlignment binding 2019-12-09 14:55:20 -06:00
John Colvin 70398935aa market view row 'inside working orders' comparison to bbo was backwards 2019-12-09 14:55:20 -06:00
John Colvin 9c571008a6 MarketViewVM does not derive from SecurityMDGrid 2019-12-09 14:55:20 -06:00
John Colvin 9165932fce clip mview animations to scroll content presenter bounds 2019-12-09 14:55:20 -06:00
John Colvin 86a56650b8 factor out pnl auxiliary popups for general use (mview) 2019-12-09 14:55:16 -06:00
John Colvin e70d826af2 introduce WindowStyle.UnsafeWindow dp 2019-11-25 12:58:11 -06:00
John Colvin 0660657d75 refactor ChildBounds extensions to be for UIElement 2019-11-25 12:58:11 -06:00
John Colvin e1ecdb5ee6 OrderTypeItem template uses Rectangle instead of Badge (the latter has some unresolved rounding issues) 2019-11-25 12:58:11 -06:00
John Colvin 76c57a5f87 WPFHelper.measure_content() rounds to layout correctly 2019-11-25 12:58:11 -06:00
John Colvin 8fd9de6cf2 fix WPFHelper.measure_visual_content - 'left edge' calculation for right align; 'bottom edge' for bottom align 2019-11-25 12:58:11 -06:00
John Colvin e19e6f2074 fix HyperlinkCell Alignment issues 2019-11-25 12:58:11 -06:00
John Colvin 0ab6a01ef5 DIYGrid CellRender.draw_text with layout rounding 2019-11-25 12:58:11 -06:00
104 changed files with 4987 additions and 1048 deletions

No files matched your search

+2 -2
View File
@@ -39,7 +39,7 @@ namespace bts {
_relay.set_token(_token.Value); _relay.set_token(_token.Value);
_dispose.Add( _dispose.Add(
_ss.Value.subscribei_metadata() _ss.Value.subscribei_metadata()
.Select(upd => upd.all.ToDictionary(i => i.SecurityKey, i => i.Strategy)) .Select(upd => upd.all.Where(i => i.HasStrategy).ToDictionary(i => i.SecurityKey, i => i.Strategy))
.Subscribe(t => { .Subscribe(t => {
var deleted_synthetic_keys = new HashSet<uint>(t.Where(kv => kv.Value.Deleted).Select(kv => kv.Key)); var deleted_synthetic_keys = new HashSet<uint>(t.Where(kv => kv.Value.Deleted).Select(kv => kv.Key));
// add back 'undeleted' synthetics // add back 'undeleted' synthetics
@@ -64,4 +64,4 @@ namespace bts {
Task.Run(run); Task.Run(run);
} }
} }
} }
+2
View File
@@ -40,6 +40,7 @@ namespace mbts.ui {
EditDocumentAltGeometryKey = nameof(EditDocumentAltGeometryKey), EditDocumentAltGeometryKey = nameof(EditDocumentAltGeometryKey),
EditDocumentGeometryKey = nameof(EditDocumentGeometryKey), EditDocumentGeometryKey = nameof(EditDocumentGeometryKey),
GearGeometryKey = nameof(GearGeometryKey), GearGeometryKey = nameof(GearGeometryKey),
HamburgerMenuGeometryKey = nameof(HamburgerMenuGeometryKey),
HornGeometryKey = nameof(HornGeometryKey), HornGeometryKey = nameof(HornGeometryKey),
KeyGeometryKey = nameof(KeyGeometryKey), KeyGeometryKey = nameof(KeyGeometryKey),
LetterAKey = nameof(LetterAKey), LetterAKey = nameof(LetterAKey),
@@ -172,6 +173,7 @@ namespace mbts.ui {
public static ImageSource FilterActive { get { return load_resource_and_freeze("FilterActive"); } } public static ImageSource FilterActive { get { return load_resource_and_freeze("FilterActive"); } }
public static ImageSource FilterError { get { return load_resource_and_freeze("FilterError"); } } public static ImageSource FilterError { get { return load_resource_and_freeze("FilterError"); } }
public static ImageSource Gear => create_icon(GearGeometryKey); public static ImageSource Gear => create_icon(GearGeometryKey);
public static ImageSource HamburgerMenu => create_icon(HamburgerMenuGeometryKey);
public static ImageSource Horn => create_icon(HornGeometryKey); public static ImageSource Horn => create_icon(HornGeometryKey);
public static ImageSource Import => load_resource_and_freeze("Import"); public static ImageSource Import => load_resource_and_freeze("Import");
public static ImageSource Key => create_icon(KeyGeometryKey); public static ImageSource Key => create_icon(KeyGeometryKey);
@@ -272,6 +272,10 @@
M16.000015,9.6000061C12.500012,9.6000061 9.5999844,12.5 9.5999844,16 9.5999844,19.5 12.500012,22.399994 16.000015,22.399994 19.500019,22.399994 22.400015,19.5 22.400015,16 22.400015,12.5 19.500019,9.6000061 16.000015,9.6000061z M14.199995,0L17.800005,0C18.199999,0,18.599993,0.29998779,18.599993,0.79998779L18.599993,4.7999878C19.900013,5.1000061,21.000019,5.6000061,22.099997,6.2999878L25.000023,3.3999939C25.099999,3.2999878 25.300011,3.1999817 25.500025,3.1999817 25.700007,3.1999817 25.900019,3.2999878 26.000025,3.3999939L28.600033,6C28.900021,6.2999878,28.900021,6.7999878,28.600033,7.1000061L25.700007,10C26.400019,11.100006,26.900019,12.299988,27.200007,13.5L31.20001,13.5C31.600037,13.5,31.999998,13.799988,31.999998,14.299988L31.999998,17.899994C31.999998,18.299988,31.700012,18.699982,31.20001,18.699982L27.200007,18.699982C26.900019,20,26.400019,21.100006,25.700007,22.199982L28.600033,25.100006C28.700009,25.199982 28.799984,25.399994 28.799984,25.600006 28.799984,25.799988 28.700009,26 28.600033,26.100006L26.000025,28.600006C25.900019,28.699982 25.700007,28.799988 25.500025,28.799988 25.300011,28.799988 25.099999,28.699982 25.000023,28.600006L22.099997,25.699982C21.000019,26.399994,19.800007,26.899994,18.599993,27.199982L18.599993,31.199982C18.599993,31.600006,18.300005,32,17.800005,32L14.199995,32C13.8,32,13.400006,31.699982,13.400006,31.199982L13.400006,27.199982C12.099987,26.899994,11.000011,26.399994,9.9000027,25.699982L7.0000064,28.600006C6.9000003,28.699982 6.6999881,28.799988 6.5000059,28.799988 6.2999937,28.799988 6.099981,28.699982 6.0000054,28.600006L3.3999967,26C3.0999784,25.699982,3.0999784,25.199982,3.3999967,24.899994L6.2999937,22C5.5999805,20.899994,5.0999801,19.699982,4.7999923,18.5L0.79998828,18.5C0.39999409,18.5,-1.933513E-07,18.199982,0,17.699982L0,14.100006C-1.933513E-07,13.699982,0.2999879,13.299988,0.79998828,13.299988L4.7999923,13.299988C5.0999801,12,5.5999805,10.899994,6.2999937,9.7999878L3.3999967,7C3.2999908,6.8999939 3.1999845,6.6999817 3.1999845,6.5 3.1999845,6.2999878 3.2999908,6.1000061 3.3999967,6L6.0000054,3.3999939C6.099981,3.2999878 6.2999937,3.1999817 6.5000059,3.1999817 6.6999881,3.1999817 6.9000003,3.2999878 7.0000064,3.3999939L9.9000027,6.2999878C11.000011,5.6000061,12.199993,5.1000061,13.400006,4.7999878L13.400006,0.79998779C13.400006,0.29998779,13.8,0,14.199995,0z M16.000015,9.6000061C12.500012,9.6000061 9.5999844,12.5 9.5999844,16 9.5999844,19.5 12.500012,22.399994 16.000015,22.399994 19.500019,22.399994 22.400015,19.5 22.400015,16 22.400015,12.5 19.500019,9.6000061 16.000015,9.6000061z M14.199995,0L17.800005,0C18.199999,0,18.599993,0.29998779,18.599993,0.79998779L18.599993,4.7999878C19.900013,5.1000061,21.000019,5.6000061,22.099997,6.2999878L25.000023,3.3999939C25.099999,3.2999878 25.300011,3.1999817 25.500025,3.1999817 25.700007,3.1999817 25.900019,3.2999878 26.000025,3.3999939L28.600033,6C28.900021,6.2999878,28.900021,6.7999878,28.600033,7.1000061L25.700007,10C26.400019,11.100006,26.900019,12.299988,27.200007,13.5L31.20001,13.5C31.600037,13.5,31.999998,13.799988,31.999998,14.299988L31.999998,17.899994C31.999998,18.299988,31.700012,18.699982,31.20001,18.699982L27.200007,18.699982C26.900019,20,26.400019,21.100006,25.700007,22.199982L28.600033,25.100006C28.700009,25.199982 28.799984,25.399994 28.799984,25.600006 28.799984,25.799988 28.700009,26 28.600033,26.100006L26.000025,28.600006C25.900019,28.699982 25.700007,28.799988 25.500025,28.799988 25.300011,28.799988 25.099999,28.699982 25.000023,28.600006L22.099997,25.699982C21.000019,26.399994,19.800007,26.899994,18.599993,27.199982L18.599993,31.199982C18.599993,31.600006,18.300005,32,17.800005,32L14.199995,32C13.8,32,13.400006,31.699982,13.400006,31.199982L13.400006,27.199982C12.099987,26.899994,11.000011,26.399994,9.9000027,25.699982L7.0000064,28.600006C6.9000003,28.699982 6.6999881,28.799988 6.5000059,28.799988 6.2999937,28.799988 6.099981,28.699982 6.0000054,28.600006L3.3999967,26C3.0999784,25.699982,3.0999784,25.199982,3.3999967,24.899994L6.2999937,22C5.5999805,20.899994,5.0999801,19.699982,4.7999923,18.5L0.79998828,18.5C0.39999409,18.5,-1.933513E-07,18.199982,0,17.699982L0,14.100006C-1.933513E-07,13.699982,0.2999879,13.299988,0.79998828,13.299988L4.7999923,13.299988C5.0999801,12,5.5999805,10.899994,6.2999937,9.7999878L3.3999967,7C3.2999908,6.8999939 3.1999845,6.6999817 3.1999845,6.5 3.1999845,6.2999878 3.2999908,6.1000061 3.3999967,6L6.0000054,3.3999939C6.099981,3.2999878 6.2999937,3.1999817 6.5000059,3.1999817 6.6999881,3.1999817 6.9000003,3.2999878 7.0000064,3.3999939L9.9000027,6.2999878C11.000011,5.6000061,12.199993,5.1000061,13.400006,4.7999878L13.400006,0.79998779C13.400006,0.29998779,13.8,0,14.199995,0z
</sys:String> </sys:String>
<sys:String x:Key="{x:Static mbts:Icons.HamburgerMenuGeometryKey}">
M2.384186E-06,24L32.000004,24 32.000004,26 2.384186E-06,26z M0,11.999998L32,11.999998 32,13.999998 0,13.999998z M2.384186E-06,0L32.000004,0 32.000004,2 2.384186E-06,2z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.HornGeometryKey}"> <sys:String x:Key="{x:Static mbts:Icons.HornGeometryKey}">
M4.0499969,7.0870913C2.9519978,7.0870913 2.0249984,8.4780906 2.0249987,10.125091 2.0249984,11.771091 2.9519978,13.162091 4.0499969,13.162091 5.1479961,13.162091 6.0749954,11.771091 6.0749955,10.125091 6.0749954,8.4780906 5.1479961,7.0870913 4.0499969,7.0870913z M29.975016,3.316155C23.883831,8.2016557,11.829888,8.9691842,8.1184387,9.0896781L8.0151367,9.0928462 8.0175586,9.1059306C8.0716033,9.4352315 8.0999939,9.7760909 8.0999942,10.125091 8.0999939,10.473966 8.0716033,10.814716 8.0175586,11.143921L8.0098858,11.185364 8.193316,11.195448C12.163719,11.420399,23.994581,12.458921,29.975016,17.005057z M31.176758,0.00019051835C31.280359,-0.0022594665 31.391857,0.01889403 31.514975,0.065146674 31.908983,0.21413228 31.999985,0.59114302 31.999985,1.0121596L31.999985,19.236969C31.999985,19.653958 31.913988,20.028956 31.525991,20.179955 31.405998,20.226952 31.450981,20.250023 31.32699,20.250023 31.050991,20.250023 30.778992,20.13601 30.583986,19.925928 25.229074,14.140572 9.6001122,13.269665 7.2865356,13.172559L7.2813506,13.172345 7.1739591,13.343056C6.4304952,14.468533 5.3060585,15.187091 4.0499969,15.187091 1.8169985,15.187091 0,12.916091 0,10.125091 0,7.3330911 1.8169985,5.0620912 4.0499969,5.0620912 5.3060585,5.0620912 6.4304952,5.78065 7.1739591,6.9063042L7.2852713,7.0832756 7.3087114,7.0828188C9.6077337,7.036146 25.141474,6.4939421 30.567997,0.34315929 30.75913,0.12521249 30.948835,0.005580858 31.176758,0.00019051835z M4.0499969,7.0870913C2.9519978,7.0870913 2.0249984,8.4780906 2.0249987,10.125091 2.0249984,11.771091 2.9519978,13.162091 4.0499969,13.162091 5.1479961,13.162091 6.0749954,11.771091 6.0749955,10.125091 6.0749954,8.4780906 5.1479961,7.0870913 4.0499969,7.0870913z M29.975016,3.316155C23.883831,8.2016557,11.829888,8.9691842,8.1184387,9.0896781L8.0151367,9.0928462 8.0175586,9.1059306C8.0716033,9.4352315 8.0999939,9.7760909 8.0999942,10.125091 8.0999939,10.473966 8.0716033,10.814716 8.0175586,11.143921L8.0098858,11.185364 8.193316,11.195448C12.163719,11.420399,23.994581,12.458921,29.975016,17.005057z M31.176758,0.00019051835C31.280359,-0.0022594665 31.391857,0.01889403 31.514975,0.065146674 31.908983,0.21413228 31.999985,0.59114302 31.999985,1.0121596L31.999985,19.236969C31.999985,19.653958 31.913988,20.028956 31.525991,20.179955 31.405998,20.226952 31.450981,20.250023 31.32699,20.250023 31.050991,20.250023 30.778992,20.13601 30.583986,19.925928 25.229074,14.140572 9.6001122,13.269665 7.2865356,13.172559L7.2813506,13.172345 7.1739591,13.343056C6.4304952,14.468533 5.3060585,15.187091 4.0499969,15.187091 1.8169985,15.187091 0,12.916091 0,10.125091 0,7.3330911 1.8169985,5.0620912 4.0499969,5.0620912 5.3060585,5.0620912 6.4304952,5.78065 7.1739591,6.9063042L7.2852713,7.0832756 7.3087114,7.0828188C9.6077337,7.036146 25.141474,6.4939421 30.567997,0.34315929 30.75913,0.12521249 30.948835,0.005580858 31.176758,0.00019051835z
</sys:String> </sys:String>
@@ -0,0 +1,13 @@
using mbts.spark;
namespace mbts.ui.spark {
readonly struct MarketViewCell {
public readonly MarketViewVM.Row row;
public readonly MarketViewView.Columns column;
public MarketViewCell(MarketViewVM.Row row, MarketViewView.Columns column) {
this.row = row;
this.column = column;
}
}
}
@@ -5,6 +5,7 @@ using mbts.co2;
using mbts.spark.utilities; using mbts.spark.utilities;
using mbts.ui; using mbts.ui;
using mbts.ui.controls; using mbts.ui.controls;
using mbts.ui.shell;
using mbts.ui.spark; using mbts.ui.spark;
using mbts.ui.utility; using mbts.ui.utility;
using mbts.utils; using mbts.utils;
@@ -18,7 +19,7 @@ using System.Windows.Input;
namespace mbts.spark { namespace mbts.spark {
partial class MarketViewVM { partial class MarketViewVM {
public class Row : SecurityMDRow, IDisposable, IEquatable<Row>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM { public class Row : DisposableViewModelBase, ISecurityMDRow, IEquatable<Row>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM {
readonly IBus _bus; readonly IBus _bus;
readonly OrdersModel _orders_model; readonly OrdersModel _orders_model;
readonly AnimationManager _animation = new AnimationManager(); readonly AnimationManager _animation = new AnimationManager();
@@ -27,7 +28,6 @@ namespace mbts.spark {
readonly string _security_text, _security_key_text; readonly string _security_text, _security_key_text;
readonly Property<double> _bid_price, _ask_price, _last_price, _day_change, _settlement, _session_high, _session_low; readonly Property<double> _bid_price, _ask_price, _last_price, _day_change, _settlement, _session_high, _session_low;
readonly Property<bool> _last_price_from_spread; readonly Property<bool> _last_price_from_spread;
readonly CellProperty<int> _position;
readonly CellProperty<uint> _last_size; readonly CellProperty<uint> _last_size;
readonly CellProperty<ulong> _volume; readonly CellProperty<ulong> _volume;
readonly CellProperty<bool> _inside_bids, _inside_asks; readonly CellProperty<bool> _inside_bids, _inside_asks;
@@ -37,17 +37,18 @@ namespace mbts.spark {
readonly MyOrderSummarizer _order_summarizer = new MyOrderSummarizer(); readonly MyOrderSummarizer _order_summarizer = new MyOrderSummarizer();
readonly MDDisplayHelper.SizeFormatter _size_formatter = MDDisplayHelper.get_formatter(MarketSizeDisplay.get_default()); readonly MDDisplayHelper.SizeFormatter _size_formatter = MDDisplayHelper.get_formatter(MarketSizeDisplay.get_default());
Property<uint> _bid_direct_size, _bid_merged_size, _ask_direct_size, _ask_merged_size; Property<uint> _bid_direct_size, _bid_merged_size, _ask_direct_size, _ask_merged_size;
double _raw_day_position; double _day_position, _raw_day_position;
string _bid_merged_size_text, _ask_merged_size_text; string _bid_merged_size_text, _ask_merged_size_text;
ulong _bbo_ref, _last_ref; ulong _bbo_ref, _last_ref;
bool _is_visible;
public Row(IBus bus, SecurityMD smd, OrdersModel orders_model) : base(smd) { public Row(IBus bus, SecurityMD smd, OrdersModel orders_model) {
_bus = bus; _bus = bus;
security_md = smd;
_orders_model = orders_model; _orders_model = orders_model;
_security_text = smd.security.ToString(); _security_text = smd.security.ToString();
_security_key_text = security_key.ToString(); _security_key_text = security_key.ToString();
string format_price(double price) => security.ContractSpec.format(price); string format_price(double price) => security.ContractSpec.format(price);
_position = new CellProperty<int>(this, nameof(position), 0);
_bid_price = backing(nameof(bid_price), double.NaN); _bid_price = backing(nameof(bid_price), double.NaN);
_ask_price = backing(nameof(ask_price), double.NaN); _ask_price = backing(nameof(ask_price), double.NaN);
_last_price = backing(nameof(last_price), double.NaN); _last_price = backing(nameof(last_price), double.NaN);
@@ -91,9 +92,17 @@ namespace mbts.spark {
void on_animations_changed() => RaisePropertyChanged(nameof(animations)); void on_animations_changed() => RaisePropertyChanged(nameof(animations));
_dispose = Disposable.Create( _dispose = Disposable.Create(
_orders_model.on_security_root_orders(security.Id).OnDispatcher().Subscribe(_on_orders), _orders_model.on_security_root_orders(security.Id).OnDispatcher().Subscribe(_on_orders),
_position.OnDispatcher().Subscribe(v => _animation.animate_position(v.newval > v.oldval)),
_orders_model.on_security_positions(security.Id).OnDispatcher().Subscribe(t => { _orders_model.on_security_positions(security.Id).OnDispatcher().Subscribe(t => {
if (Set(ref _raw_day_position, t.state.Values.Sum(p => p.Item2.raw_day_pos()), nameof(raw_day_position))) bool day_pos_dirty = false;
var new_day_pos = t.state.Values.Sum(p => p.Item2.day_pos());
if (new_day_pos != _day_position) {
if (!double.IsNaN(new_day_pos) && !double.IsNaN(_day_position))
_animation.animate_position(new_day_pos > _day_position);
_day_position = new_day_pos;
RaisePropertyChanged(nameof(day_position));
day_pos_dirty = true;
}
if (day_pos_dirty | Set(ref _raw_day_position, t.state.Values.Sum(p => p.Item2.raw_day_pos()), nameof(raw_day_position)))
raise_invalidated(); raise_invalidated();
}), }),
_inside_bids.OnDispatcher().Subscribe(v => _animation.animate_working_bids_inside(v.newval)), _inside_bids.OnDispatcher().Subscribe(v => _animation.animate_working_bids_inside(v.newval)),
@@ -105,10 +114,20 @@ namespace mbts.spark {
public event Action invalidated; public event Action invalidated;
public SecurityMD security_md { get; }
public SecurityImmutable security => security_md.security;
public uint security_key => security_md.security.Id;
SecurityMD ISecurityMDRow.md => security_md;
public bool is_visible {
get => _is_visible;
set => Set(ref _is_visible, value);
}
#region Bound Properties #region Bound Properties
public bool inside_bids => _inside_bids.value; public bool inside_bids => _inside_bids.value;
public bool inside_asks => _inside_asks.value; public bool inside_asks => _inside_asks.value;
public int position => _position.value; public double day_position => _day_position;
public double raw_day_position => _raw_day_position; public double raw_day_position => _raw_day_position;
public double last_price => _last_price.Value; public double last_price => _last_price.Value;
public bool last_price_from_spread => _last_price_from_spread.Value; public bool last_price_from_spread => _last_price_from_spread.Value;
@@ -158,29 +177,30 @@ namespace mbts.spark {
public IReadOnlyList<DIYGrid.IGridCellStore> cell_stores => new DIYGrid.IGridCellStore[0]; public IReadOnlyList<DIYGrid.IGridCellStore> cell_stores => new DIYGrid.IGridCellStore[0];
#endregion #endregion
MDConsumerHandle _md => security_md.md;
public void raise_invalidated() => invalidated?.Invoke(); public void raise_invalidated() => invalidated?.Invoke();
public void refresh() { public void refresh() {
bool dirty = false; bool dirty = false;
if (md.md.get_bbo(ref _bbo_ref, out NativePriceSize b, out NativePriceSize a)) { if (_md.get_bbo(ref _bbo_ref, out NativePriceSize b, out NativePriceSize a)) {
_bid_price.set(b.price); _bid_price.set(b.price);
refresh_size(ref b, _bid_direct_size, _bid_merged_size, ref _bid_merged_size_text, nameof(bid_merged_size_text)); refresh_size(ref b, _bid_direct_size, _bid_merged_size, ref _bid_merged_size_text, nameof(bid_merged_size_text));
_ask_price.set(a.price); _ask_price.set(a.price);
refresh_size(ref a, _ask_direct_size, _ask_merged_size, ref _ask_merged_size_text, nameof(ask_merged_size_text)); refresh_size(ref a, _ask_direct_size, _ask_merged_size, ref _ask_merged_size_text, nameof(ask_merged_size_text));
_inside_bids.on_next_distinct(_bid_price.Value >= _working_best_bid.value, ref dirty); _refresh_inside_working_orers(ref dirty);
_inside_asks.on_next_distinct(_ask_price.Value <= _working_best_ask.value, ref dirty);
} }
if (md.md.get_last_trade(ref _last_ref, out NativePriceSize ps, out DateTime ts, out ulong v, out bool from_spread)) { if (_md.get_last_trade(ref _last_ref, out NativePriceSize ps, out DateTime ts, out ulong v, out bool from_spread)) {
_last_price.set(ps.price); _last_price.set(ps.price);
_last_price_from_spread.set(from_spread); _last_price_from_spread.set(from_spread);
_last_size.on_next_distinct(ps.size, ref dirty); _last_size.on_next_distinct(ps.size, ref dirty);
_volume.on_next_distinct(v, ref dirty); _volume.on_next_distinct(v, ref dirty);
} }
dirty |= _settlement.set_new(md.md.settlement_price); dirty |=
dirty |= _session_low.set_new(md.md.session_low); _settlement.set_new(_md.settlement_price) |
dirty |= _session_high.set_new(md.md.session_high); _session_low.set_new(_md.session_low) |
dirty |= _day_change.set_new(last_price - settlement); _session_high.set_new(_md.session_high) |
_volume.on_next_distinct(md.md.total_volume, ref dirty); _day_change.set_new(last_price - settlement);
if (dirty) if (dirty)
invalidated?.Invoke(); invalidated?.Invoke();
@@ -206,7 +226,7 @@ namespace mbts.spark {
security_key.GetHashCode(); security_key.GetHashCode();
#region Show Windows #region Show Windows
void _show_ladder() => _bus.post(SparkTags.ShowLadderTag, md); void _show_ladder() => _bus.post(SparkTags.ShowLadderTag, security_md);
void _show_order_book(MarketViewView.Columns col) { void _show_order_book(MarketViewView.Columns col) {
switch (col) { switch (col) {
@@ -275,14 +295,11 @@ namespace mbts.spark {
} }
void _refresh_orders(ref bool dirty) { void _refresh_orders(ref bool dirty) {
_position.on_next_distinct(_order_summarizer.position, ref dirty);
_working_bid_volume.on_next_distinct(_order_summarizer.working_bid_qty, ref dirty); _working_bid_volume.on_next_distinct(_order_summarizer.working_bid_qty, ref dirty);
_working_ask_volume.on_next_distinct(_order_summarizer.working_ask_qty, ref dirty); _working_ask_volume.on_next_distinct(_order_summarizer.working_ask_qty, ref dirty);
_working_best_bid.on_next_distinct(_order_summarizer.best_working_bid, ref dirty); _working_best_bid.on_next_distinct(_order_summarizer.best_working_bid, ref dirty);
_working_best_ask.on_next_distinct(_order_summarizer.best_working_ask, ref dirty); _working_best_ask.on_next_distinct(_order_summarizer.best_working_ask, ref dirty);
_inside_bids.on_next_distinct(_order_summarizer.best_working_bid >= bid_price, ref dirty); _refresh_inside_working_orers(ref dirty);
_inside_asks.on_next_distinct(_order_summarizer.best_working_ask <= ask_price, ref dirty);
RaisePropertyChanged( RaisePropertyChanged(
// Implied might not be ever set, so it probably does not RaisePropertyChanged either // Implied might not be ever set, so it probably does not RaisePropertyChanged either
// This might be part of the filter funk? // This might be part of the filter funk?
@@ -292,6 +309,11 @@ namespace mbts.spark {
nameof(working_asks_text) nameof(working_asks_text)
); );
} }
void _refresh_inside_working_orers(ref bool dirty) {
_inside_bids.on_next_distinct(!double.IsNaN(working_best_bid) && OrderDataHelper.PriceComparer.Compare(working_best_bid, bid_price) >= 0, ref dirty);
_inside_asks.on_next_distinct(!double.IsNaN(working_best_ask) && OrderDataHelper.PriceComparer.Compare(working_best_ask, ask_price) <= 0, ref dirty);
}
#endregion #endregion
class MyOrderSummarizer { class MyOrderSummarizer {
@@ -367,4 +389,4 @@ namespace mbts.spark {
} }
} }
} }
} }
@@ -1,15 +1,30 @@
using bts;
using bts.api; using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.collections; using bts.collections;
using bts.utils; using bts.utils;
using mbts.persist; using mbts.persist;
using mbts.spark.filters; using mbts.spark.filters;
using mbts.spark.utilities;
using mbts.ui; using mbts.ui;
using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.settings; using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.utility; using mbts.ui.utility;
using mbts.utils;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Media; using System.Windows.Media;
using static bts.shell.MarketViewWindowFactory; using static bts.shell.MarketViewWindowFactory;
@@ -17,21 +32,61 @@ using static mbts.ui.controls.DIYGrid;
using static mbts.ui.spark.MarketViewView; using static mbts.ui.spark.MarketViewView;
namespace mbts.spark { namespace mbts.spark {
partial class MarketViewVM : SecurityMDGrid<MarketViewVM.Row, SecurityMD> { /// <summary>
/// Viewmodel class designed for <see cref="ui.spark.MarketViewView"/>
/// </summary>
partial class MarketViewVM : DisposableViewModelBase, IHandleRowSelection {
static readonly IReadOnlyList<Func<MarketViewVM, IDataGridColumnFilter<Row>>> _filter_getters =
ObjectSnapshot.property_delegates_of_type<MarketViewVM, IDataGridColumnFilter<Row>>().ToReadOnlyList();
static readonly IComparer<SecurityMD> _sec_md_key_comparer = Comparer<uint>.Default.wrap(SecurityMD.key_fn);
static readonly IComparer<Row> _row_key_comparer = _sec_md_key_comparer.wrap<SecurityMD, Row>(r => r.security_md);
static readonly string _security_delimiter = $" {SpecialCharacters.Dot} ";
readonly IBus _bus; readonly IBus _bus;
readonly OrdersModel _orders_model; readonly OrdersModel _orders_model;
IWindowSettingsManager<GridSettings> _settings_manager; readonly ObservableCollection<Row> _rows = new ObservableCollection<Row>();
readonly IList<SecurityMD> _wrapped_rows;
readonly ListCollectionView _rows_view;
readonly Dictionary<uint, Row> _cache = new Dictionary<uint, Row>();
readonly Property<Row> _current_row;
readonly DeferrableActionWrapper _refresh_filter;
Func<Row, bool> _filter;
IComparer<Row> _comparer;
Color _selection_highlight;
public MarketViewVM(IBus bus, OrdersModel orders_model, IObservable<StartupData> state, IWindowSettingsManager<GridSettings> settings_manager ) /// <summary>
: this(bus, orders_model, state, state.SelectManyInSeries(s => s.security_criteria.subscribe_md(bus)), settings_manager) { } /// Initializes an instance of the <see cref="ui.spark.MarketViewView"/> class.
/// </summary>
// securities_connectable should NOT be connected already. /// <param name="bus"></param>
MarketViewVM(IBus bus, OrdersModel orders_model, IObservable<StartupData> state, IObservable<IEnumerable<SecurityMD>> securities_source, IWindowSettingsManager<GridSettings> settings_manager) /// <param name="orders_model"></param>
: base(RXCollection.Create(securities_source, SecurityDataHelper.EqualityComparer.MDComparer), null) { /// <param name="security_mds_source"></param>
/// <param name="use_mouse_state_transitions">Indicates whether or not hyperlink cells should use visual states to animate mouse over (seems to be slower than style triggers, should investigate to be certain).</param>
public MarketViewVM(
IBus bus,
OrdersModel orders_model,
IObservable<TableUpdate<SecurityMD, uint>> security_mds_source,
bool use_mouse_state_transitions = false) {
_bus = bus; _bus = bus;
_orders_model = orders_model; _orders_model = orders_model;
security_filter = new RegexFilterVM<Row>(r => r.security.ToString(), nameof(Row.security)); security_filter = new RegexFilterVM<Row>(r => r.security.ToString(), nameof(Row.security));
_settings_manager = settings_manager; // rows
_wrapped_rows = _rows.WrapSelector(r => r.security_md, s => {
var r = new Row(_bus, s, _orders_model);
r.is_visible = _filter == null || _filter(r);
return r;
});
_current_row = backing<Row>(nameof(current_row));
_rows_view = new ListCollectionView(_rows) {
Filter = obj => obj is Row r && r.is_visible,
IsLiveFiltering = true
};
_rows_view.LiveFilteringProperties.Add(nameof(Row.is_visible));
// Important: these selected_security/md wrappers should be instantiated in the constructor (rather than lazily),
// to prevent situations where callers subscribe to the selected_rows.CollectionChanged event before the wrappers do.
// This way, the wrappers are protected from unintended side effects of the foreign callbacks, as they will always receive CollectionChange notifications first.
selected_securities = selected_rows.SelectObservable(r => r.security);
selected_security_mds = selected_rows.SelectObservable(r => r.security_md);
// Columns // Columns
const string merged_size_col_header = "Qty", direct_size_col_header = "Direct", implied_size_col_header = "Implied", working_col_header = "Working"; const string merged_size_col_header = "Qty", direct_size_col_header = "Direct", implied_size_col_header = "Implied", working_col_header = "Working";
const double working_orders_col_width = 105; const double working_orders_col_width = 105;
@@ -39,24 +94,55 @@ namespace mbts.spark {
add_col(Columns.Security, "Security", r => r.security.ToString(), nameof(Row.security), DefaultColumnWidths.Security, security_filter, DataGridFilterKnownTemplates.Regex); add_col(Columns.Security, "Security", r => r.security.ToString(), nameof(Row.security), DefaultColumnWidths.Security, security_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.Volume, "Volume", r => r.volume.ToString(), nameof(Row.volume), DefaultColumnWidths.Volume, volume_filter, DataGridFilterKnownTemplates.ULongMinMax); add_col(Columns.Volume, "Volume", r => r.volume.ToString(), nameof(Row.volume), DefaultColumnWidths.Volume, volume_filter, DataGridFilterKnownTemplates.ULongMinMax);
add_col(Columns.LastSpd, "Spd", r => r.last_price_from_spread ? "S" : "", nameof(Row.last_price_from_spread), DefaultColumnWidths.Side, last_price_from_spread_filter, DataGridFilterKnownTemplates.Regex); add_col(Columns.LastSpd, "Spd", r => r.last_price_from_spread ? "S" : "", nameof(Row.last_price_from_spread), DefaultColumnWidths.Side, last_price_from_spread_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.Last, "Last", r => r.format_price(r.last_price), nameof(Row.last_price), DefaultColumnWidths.Price, last_price_filter, DataGridFilterKnownTemplates.DoubleMinMax); add_col(Columns.Last, "Last", r => r.format_price(r.last_price), nameof(Row.last_price), DefaultColumnWidths.Price, last_price_filter, DataGridFilterKnownTemplates.DoubleMinMax);
add_col(Columns.LastSize, merged_size_col_header, r => r.last_size.ToString(), nameof(Row.last_size), DefaultColumnWidths.Size, last_size_filter, DataGridFilterKnownTemplates.UIntMinMax, h_alignment: System.Windows.HorizontalAlignment.Right); add_col(Columns.LastSize, merged_size_col_header, r => r.last_size.ToString(), nameof(Row.last_size), DefaultColumnWidths.Size, last_size_filter, DataGridFilterKnownTemplates.UIntMinMax);
add_col(Columns.Position, "Pos", r => r.position.ToString(), nameof(Row.position), DefaultColumnWidths.Size, position_filter, DataGridFilterKnownTemplates.IntMinMax, true, h_alignment: System.Windows.HorizontalAlignment.Right); add_hl_col(
add_col(Columns.RawDayPosition, "Raw Day Pos", r => SparkUtils.fmt_position(r.raw_day_position), nameof(Row.raw_day_position), DefaultColumnWidths.Size, raw_day_position_filter, DataGridFilterKnownTemplates.DoubleMinMax, true, h_alignment: System.Windows.HorizontalAlignment.Right); Columns.Position,
add_hl_working_orders_col(Columns.WorkingBids, working_col_header, nameof(Row.working_bids_text), nameof(Row.working_best_bid), nameof(Row.working_bids_click), working_bid_volume_filter, BTSColors.MarketData.bid, System.Windows.HorizontalAlignment.Right); "Day Pos",
add_col(Columns.BidImpliedSize, implied_size_col_header, r => r.bid_implied_size.ToString(), nameof(Row.bid_implied_size), DefaultColumnWidths.ImpliedDirectMergedSize, bid_implied_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); new Binding(nameof(Row.day_position)),
add_col(Columns.BidDirectSize, direct_size_col_header, r => r.bid_direct_size.ToString(), nameof(Row.bid_direct_size), DefaultColumnWidths.ImpliedDirectMergedSize, bid_direct_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); nameof(Row.day_position),
add_hl_merged_size_col(Columns.BidMergedSize, merged_size_col_header, nameof(Row.bid_merged_size), nameof(Row.bid_merged_size_text), nameof(Row.bid_merged_size_click), bid_merged_size_filter, BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); day_position_filter,
add_hl_price_col(Columns.Bid, "Bid", nameof(Row.bid_price), nameof(Row.bid_price_click), bid_price_filter, BTSColors.header_text, BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); DataGridFilterKnownTemplates.IntMinMax,
add_hl_price_col(Columns.Ask, "Ask", nameof(Row.ask_price), nameof(Row.ask_price_click), ask_price_filter, BTSColors.header_text, BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); DefaultColumnWidths.Size,
add_hl_merged_size_col(Columns.AskMergedSize, merged_size_col_header, nameof(Row.ask_merged_size), nameof(Row.ask_merged_size_text), nameof(Row.ask_merged_size_click), ask_merged_size_filter, BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); tooltip: $"Show {_fills_title(Columns.Position).desc}");
add_col(Columns.AskDirectSize, direct_size_col_header, r => r.ask_direct_size.ToString(), nameof(Row.ask_direct_size), DefaultColumnWidths.ImpliedDirectMergedSize, ask_direct_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); add_hl_col(
add_col(Columns.AskImpliedSize, implied_size_col_header, r => r.ask_implied_size.ToString(), nameof(Row.ask_implied_size), DefaultColumnWidths.ImpliedDirectMergedSize, ask_implied_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); Columns.RawDayPosition,
add_hl_working_orders_col(Columns.WorkingAsks, working_col_header, nameof(Row.working_asks_text), nameof(Row.working_best_ask), nameof(Row.working_asks_click), working_ask_volume_filter, BTSColors.MarketData.ask, System.Windows.HorizontalAlignment.Right); "Raw Day Pos",
add_col(Columns.Settlement, "Settlement", r => r.format_price(r.settlement), nameof(Row.settlement), DefaultColumnWidths.Settlement, settlement_filter, DataGridFilterKnownTemplates.DoubleMinMax, h_alignment: System.Windows.HorizontalAlignment.Right); new Binding(nameof(Row.raw_day_position)) {
add_col(Columns.DayChange, "Change", r => r.format_price(r.day_change), nameof(Row.day_change), DefaultColumnWidths.Price, day_change_filter, DataGridFilterKnownTemplates.DoubleMinMax, true, h_alignment: System.Windows.HorizontalAlignment.Right); Converter = ValueConverter.create<double, string>(SparkUtils.fmt_position)
add_col(Columns.SessionLow, "Low", r => r.format_price(r.session_low), nameof(Row.session_low), DefaultColumnWidths.Price, session_low_filter, DataGridFilterKnownTemplates.DoubleMinMax, h_alignment: System.Windows.HorizontalAlignment.Right); },
add_col(Columns.SessionHigh, "High", r => r.format_price(r.session_high), nameof(Row.session_high), DefaultColumnWidths.Price, session_high_filter, DataGridFilterKnownTemplates.DoubleMinMax, h_alignment: System.Windows.HorizontalAlignment.Right); nameof(Row.raw_day_position),
raw_day_position_filter,
DataGridFilterKnownTemplates.DoubleMinMax,
DefaultColumnWidths.Size,
tooltip: $"Show {_fills_title(Columns.RawDayPosition).desc}");
add_hl_working_orders_col(
Columns.WorkingBids,
working_col_header,
nameof(Row.working_bids_text),
nameof(Row.working_best_bid),
working_bid_volume_filter,
BTSColors.MarketData.bid);
add_col(Columns.BidImpliedSize, implied_size_col_header, r => r.bid_implied_size.ToString(), nameof(Row.bid_implied_size), DefaultColumnWidths.ImpliedDirectMergedSize, bid_implied_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.bid);
add_col(Columns.BidDirectSize, direct_size_col_header, r => r.bid_direct_size.ToString(), nameof(Row.bid_direct_size), DefaultColumnWidths.ImpliedDirectMergedSize, bid_direct_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.bid);
add_hl_merged_size_col(Columns.BidMergedSize, nameof(Row.bid_merged_size), nameof(Row.bid_merged_size_text), bid_merged_size_filter, BTSColors.MarketData.bid);
add_hl_price_col(Columns.Bid, "Bid", nameof(Row.bid_price), bid_price_filter, BTSColors.header_text, BTSColors.MarketData.bid);
add_hl_price_col(Columns.Ask, "Ask", nameof(Row.ask_price), ask_price_filter, BTSColors.header_text, BTSColors.MarketData.ask);
add_hl_merged_size_col(Columns.AskMergedSize, nameof(Row.ask_merged_size), nameof(Row.ask_merged_size_text), ask_merged_size_filter, BTSColors.MarketData.ask);
add_col(Columns.AskDirectSize, direct_size_col_header, r => r.ask_direct_size.ToString(), nameof(Row.ask_direct_size), DefaultColumnWidths.ImpliedDirectMergedSize, ask_direct_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.ask);
add_col(Columns.AskImpliedSize, implied_size_col_header, r => r.ask_implied_size.ToString(), nameof(Row.ask_implied_size), DefaultColumnWidths.ImpliedDirectMergedSize, ask_implied_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.ask);
add_hl_working_orders_col(
Columns.WorkingAsks,
working_col_header,
nameof(Row.working_asks_text),
nameof(Row.working_best_ask),
working_ask_volume_filter,
BTSColors.MarketData.ask);
add_col(Columns.Settlement, "Settlement", r => r.format_price(r.settlement), nameof(Row.settlement), DefaultColumnWidths.Settlement, settlement_filter, DataGridFilterKnownTemplates.DoubleMinMax);
add_col(Columns.DayChange, "Change", r => r.format_price(r.day_change), nameof(Row.day_change), DefaultColumnWidths.Price, day_change_filter, DataGridFilterKnownTemplates.DoubleMinMax, true);
add_col(Columns.SessionLow, "Low", r => r.format_price(r.session_low), nameof(Row.session_low), DefaultColumnWidths.Price, session_low_filter, DataGridFilterKnownTemplates.DoubleMinMax);
add_col(Columns.SessionHigh, "High", r => r.format_price(r.session_high), nameof(Row.session_high), DefaultColumnWidths.Price, session_high_filter, DataGridFilterKnownTemplates.DoubleMinMax);
add_col(Columns.SecurityKey, "Security Key", r => r.security_key.ToString(), nameof(Row.security_key), DefaultColumnWidths.SecurityKey, security_key_filter, DataGridFilterKnownTemplates.Regex); add_col(Columns.SecurityKey, "Security Key", r => r.security_key.ToString(), nameof(Row.security_key), DefaultColumnWidths.SecurityKey, security_key_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.MarketDescription, "Market Description", r => r.security.market_description(), nameof(Row.market_description), DefaultColumnWidths.SecurityKey, market_description_filter, DataGridFilterKnownTemplates.Regex); add_col(Columns.MarketDescription, "Market Description", r => r.security.market_description(), nameof(Row.market_description), DefaultColumnWidths.SecurityKey, market_description_filter, DataGridFilterKnownTemplates.Regex);
@@ -65,9 +151,32 @@ namespace mbts.spark {
add_col(Columns.HubAlias, "Hub Alias", r => r.security.hub_alias(), nameof(Row.hub_alias), DefaultColumnWidths.SecurityKey, hub_alias_filter, DataGridFilterKnownTemplates.Regex); add_col(Columns.HubAlias, "Hub Alias", r => r.security.hub_alias(), nameof(Row.hub_alias), DefaultColumnWidths.SecurityKey, hub_alias_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.StripName, "Strip Name", r => r.security.strip_name(), nameof(Row.strip_name), DefaultColumnWidths.SecurityKey, strip_name_filter, DataGridFilterKnownTemplates.Regex); add_col(Columns.StripName, "Strip Name", r => r.security.strip_name(), nameof(Row.strip_name), DefaultColumnWidths.SecurityKey, strip_name_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.MicCode, "Mic Code", r => r.security.mic_code(), nameof(Row.mic_code), DefaultColumnWidths.SecurityKey, mic_code_filter, DataGridFilterKnownTemplates.Regex); add_col(Columns.MicCode, "Mic Code", r => r.security.mic_code(), nameof(Row.mic_code), DefaultColumnWidths.SecurityKey, mic_code_filter, DataGridFilterKnownTemplates.Regex);
// // row vm filter
void add_col(Columns col_key, string header, Func<Row, string> get_text, string prop, double width, IDataGridColumnFilter filter, string filter_template, bool is_animatable = false, Color? font_color = null, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) => // Althoguh securities are filtered at the row 'model' level (SecurityMD), the column base filters have to be applied at the row vm level,
columns.Add(new RenderTextColumn<Row, Columns>(col_key, get_text, filter, filter_template) { // because they access market data, which is polled periodically and cached in the row vm.
_refresh_filter = new DeferrableActionWrapper(() => _filter_changed?.Invoke());
var row_filter_source = Observable.Create<Func<Row, bool>>(o => {
notify();
_filter_changed += notify;
return Disposable.Create(() => _filter_changed -= notify);
void notify() =>
o.OnNext(get_filter_states().build_predicate());
});
foreach (var f in _all_filters) {
f.filter_changed += _refresh_filter.execute;
}
_dispose = Disposable.Create(
row_filter_source.Subscribe(f => {
// the rows are polled every 100 ms, just set the filter and let the refresh take care of the rest.
_filter = f;
}),
security_mds_source.Subscribe(_on_securities),
ObservableAutoWrapper.connect_item_hooks(_rows, r => r, true),
WorkLoop.Start("MarketView", _refresh)
);
// local methods
RenderTextColumn<Row> add_col(Columns col_key, string header, Func<Row, string> get_text, string prop, double width, IDataGridColumnFilter filter, string filter_template, bool is_animatable = false, Color? font_color = null, HorizontalAlignment h_alignment = HorizontalAlignment.Right) {
var col = new RenderTextColumn<Row, Columns>(col_key, get_text, filter, filter_template) {
// it's necessary to have this id populated for grid settings // it's necessary to have this id populated for grid settings
id = bts.shell.MarketViewWindowFactory.col_id(col_key), id = bts.shell.MarketViewWindowFactory.col_id(col_key),
Header = header, Header = header,
@@ -76,31 +185,91 @@ namespace mbts.spark {
padding = is_animatable ? AnimatableCellPadding : DefaultCellPadding, padding = is_animatable ? AnimatableCellPadding : DefaultCellPadding,
font_color_override = font_color, font_color_override = font_color,
horizontal_alignment = h_alignment horizontal_alignment = h_alignment
}); };
columns.Add(col);
return col;
}
void add_hl_price_col(Columns col_key, string header, string prop, string command_prop, IDataGridColumnFilter filter, Color foreground, Color? background, System.Windows.HorizontalAlignment h_alignment) => void add_hl_price_col(Columns col_key, string header, string prop, IDataGridColumnFilter filter, Color foreground, Color? background) =>
add_hl_col(col_key, header, price_binding(prop), prop, command_prop, filter, DataGridFilterKnownTemplates.DoubleMinMax, DefaultColumnWidths.MViewPrice, foreground, background, h_alignment); add_hl_col(
col_key,
header,
price_binding(prop),
prop,
filter,
DataGridFilterKnownTemplates.DoubleMinMax,
DefaultColumnWidths.MViewPrice,
foreground,
background,
tooltip: _order_ticket_tooltip(col_key));
void add_hl_merged_size_col(Columns col_key, string header, string sort_prop, string text_prop, string command_prop, IDataGridColumnFilter filter, Color foreground, System.Windows.HorizontalAlignment h_alignment) => void add_hl_merged_size_col(Columns col_key, string sort_prop, string text_prop, IDataGridColumnFilter filter, Color foreground) =>
add_hl_col(col_key, header, new Binding(text_prop), sort_prop, command_prop, filter, DataGridFilterKnownTemplates.UIntMinMax, DefaultColumnWidths.ImpliedDirectMergedSize, foreground, null, h_alignment); add_hl_col(
col_key,
merged_size_col_header,
new Binding(text_prop),
sort_prop,
filter,
DataGridFilterKnownTemplates.UIntMinMax,
DefaultColumnWidths.ImpliedDirectMergedSize,
foreground,
tooltip: _order_ticket_tooltip(col_key));
void add_hl_working_orders_col(Columns col_key, string header, string text_prop, string sort_prop, string command_prop, IDataGridColumnFilter filter, Color foreground, System.Windows.HorizontalAlignment h_alignment) => HyperlinkElementColumn<Columns> add_hl_working_orders_col(Columns col_key, string header, string text_prop, string sort_prop, IDataGridColumnFilter filter, Color foreground) =>
add_hl_col(col_key, header, new Binding(text_prop), sort_prop, command_prop, filter, DataGridFilterKnownTemplates.IntMinMax, working_orders_col_width, foreground, null, h_alignment); add_hl_col(
col_key,
header,
new Binding(text_prop),
sort_prop,
filter,
DataGridFilterKnownTemplates.IntMinMax,
working_orders_col_width,
foreground,
tooltip: $"Show {_orderbook_title(col_key).desc}");
void add_hl_col( HyperlinkElementColumn<Columns> add_hl_col(
Columns col_key, string header, BindingBase binding, string prop, string command_prop, Columns col_key,
IDataGridColumnFilter filter, string filter_template, double width, Color foreground, Color? background, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) => string header,
columns.Add(new HyperlinkElementColumn<Row, Columns>( BindingBase binding,
col_key, binding, new Binding(command_prop), filter, filter_template) { string prop,
// it's necessary to have this id populated for grid settings IDataGridColumnFilter filter,
id = bts.shell.MarketViewWindowFactory.col_id(col_key), string filter_template,
Header = header, double width,
sort_member_path = prop, Color? foreground = null,
font_color_override = foreground, Color? background = null,
background_color_override = background, HorizontalAlignment h_alignment = HorizontalAlignment.Right,
Width = DefaultColumnWidths.Price, string tooltip = null,
horizontal_alignment = h_alignment BindingBase tooltip_binding = null) {
});
var col = new HyperlinkElementColumn<Columns>(
col_key, filter, filter_template) {
// it's necessary to have this id populated for grid settings
id = bts.shell.MarketViewWindowFactory.col_id(col_key),
Header = header,
sort_member_path = prop,
font_color_override = foreground,
background_color_override = background,
TextBinding = binding,
Width = DefaultColumnWidths.Price,
horizontal_alignment = h_alignment
};
col.view_generated += on_view_generated;
columns.Add(col);
return col;
//
void on_view_generated(HyperlinkCell cell_view) {
cell_view.SetValue(ColumnKeyProperty, col_key);
cell_view.SetValue(ColumnProperty, col);
cell_view.SetBinding(GridProperty, new Binding { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DIYGrid), 1) });
if (tooltip != null) {
cell_view.ToolTip = tooltip;
} else if (tooltip_binding != null) {
cell_view.SetBinding(FrameworkElement.ToolTipProperty, tooltip_binding);
}
if (use_mouse_state_transitions)
init_hyperlink_hover_animation(cell_view, col);
}
}
BindingBase price_binding(string prop) { BindingBase price_binding(string prop) {
var mb = new MultiBinding { Converter = price_converter }; var mb = new MultiBinding { Converter = price_converter };
@@ -108,72 +277,95 @@ namespace mbts.spark {
mb.Bindings.Add(new Binding($"{nameof(Row.security)}.{nameof(SecurityImmutable.ContractSpec)}") { Mode = BindingMode.OneWay }); mb.Bindings.Add(new Binding($"{nameof(Row.security)}.{nameof(SecurityImmutable.ContractSpec)}") { Mode = BindingMode.OneWay });
return mb; return mb;
} }
//
// make font-color immutable for Side, Size, (the font-color rule is hard-coded: MarketData.bid for Buy orders, MarketData.ask for Sells) void init_hyperlink_hover_animation(HyperlinkCell cell_view, ColumnBase col) {
var col_settings_flags = new Dictionary<string, GridColumnSettingsFeatureFlags> { // background timeline
{ Columns.Bid.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor | GridColumnSettingsFeatureFlags.ImmutableBackgroundColor }, var hover_bg_timeline = VisualStateHelper.create_color_animation(
{ Columns.Ask.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor | GridColumnSettingsFeatureFlags.ImmutableBackgroundColor}, cell_view,
{ Columns.WorkingAsks.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, new PropertyPath("(0).(1)", HyperlinkCell.BackgroundProperty, SolidColorBrush.ColorProperty),
{ Columns.WorkingBids.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor } new Binding(nameof(ColumnBase.background_color)) {
}; Source = col,
grid_settings_manager = new SimpleGridSettingsManager<Row>(columns, col_settings_flags, row_vms); Converter = new ColorBlendConverter { Overlay = Colors.Black.with(0x1A) }
// this will initialize the immutable properties that correspond to the col_settings_flags above (e.g. Bid/Ask font_color_override, etc.) });
grid_settings_manager.load_from(settings_manager.current_settings()); // background pressed timeline
// var pressed_bg_timeline = VisualStateHelper.create_color_animation(
_resources.AddRange( cell_view,
state.OnDispatcher().Subscribe(s => { new PropertyPath("(0).(1)", HyperlinkCell.BackgroundProperty, SolidColorBrush.ColorProperty),
using (rows_view.DeferRefresh()) { new Binding(nameof(ColumnBase.background_color)) {
if (s.grid != null) { Source = col,
// this means we are not using defaults, Converter = new ColorBlendConverter { Overlay = Colors.Black.with(0x25) }
// Note: settings_manager in turn notifies grid_settings_manager of this update });
_settings_manager.instance_settings = s.grid; // border timeline
var bd_brush = new SolidColorBrush();
BindingOperations.SetBinding(bd_brush, SolidColorBrush.ColorProperty, new Binding(nameof(ColumnBase.background_color)) { Source = col });
cell_view.BorderBrush = bd_brush;
cell_view.BorderThickness = new Thickness(1);
var hover_bd_timeline = VisualStateHelper.create_color_animation(
cell_view, new PropertyPath("(0).(1)", HyperlinkCell.BorderBrushProperty, SolidColorBrush.ColorProperty), Colors.Black.with(0x60));
// mouse states
VisualStateManager.GetVisualStateGroups(cell_view).Add(
VisualStateHelper.create_group("MouseStates",
new VisualState { Name = "Normal" },
VisualStateHelper.create_state("MouseOver", hover_bg_timeline, hover_bd_timeline),
VisualStateHelper.create_state("Pressed", pressed_bg_timeline, hover_bd_timeline)));
// state groups manager
StateManager.SetGroups(cell_view, new StateGroupsManager {
StateDefinitions = new StateDefinitionCollection {
new MouseStateDefinition { MouseSource = cell_view }
} }
if (s.filters is FilterStates filters) { });
security_filter.load_state(filters.security); }
bid_price_filter.load_state(filters.bid_price);
bid_merged_size_filter.load_state(filters.bid_merged_size);
bid_direct_size_filter.load_state(filters.bid_direct_size);
bid_implied_size_filter.load_state(filters.bid_implied_size);
ask_price_filter.load_state(filters.ask_price);
ask_merged_size_filter.load_state(filters.ask_merged_size);
ask_direct_size_filter.load_state(filters.ask_direct_size);
ask_implied_size_filter.load_state(filters.ask_implied_size);
last_price_filter.load_state(filters.last_price);
last_price_from_spread_filter.load_state(filters.last_price_from_spread);
last_size_filter.load_state(filters.last_size);
day_change_filter.load_state(filters.day_change);
settlement_filter.load_state(filters.settlement);
session_low_filter.load_state(filters.session_low);
session_high_filter.load_state(filters.session_high);
position_filter.load_state(filters.position);
raw_day_position_filter.load_state(filters.raw_day_position);
working_bid_volume_filter.load_state(filters.working_bid_volume);
working_ask_volume_filter.load_state(filters.working_ask_volume);
volume_filter.load_state(filters.volume);
security_key_filter.load_state(filters.security_key);
}
rows_view.set_sort_descriptions(s.sorting_criterion, columns);
}
}), DataGridFilterHelper.hook_filters(rows_view, security_filter,
bid_price_filter, bid_merged_size_filter, bid_direct_size_filter, bid_implied_size_filter,
ask_price_filter, ask_merged_size_filter, ask_direct_size_filter, ask_implied_size_filter,
last_price_filter, last_price_from_spread_filter, last_size_filter, day_change_filter, settlement_filter,
session_low_filter, session_high_filter, position_filter, raw_day_position_filter, working_bid_volume_filter, working_ask_volume_filter, volume_filter, security_key_filter),
settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager),
WorkLoop.Start("MarketView", _refresh)
);
} }
public event PropertyChange<Row> current_row_changed { add => _current_row.Changed += value; remove => _current_row.Changed -= value; }
event Action _filter_changed;
public ICollectionView rows_view => _rows_view;
public ObservableCollection<Row> rows => _rows;
public ObservableCollection<Row> selected_rows { get; } = new ObservableCollection<Row>();
public IReadOnlyObservableCollection<SecurityImmutable> selected_securities { get; }
public IReadOnlyObservableCollection<SecurityMD> selected_security_mds { get; }
public Color selection_highlight { get => _selection_highlight; set => Set(ref _selection_highlight, value); }
public ObservableCollection<ColumnBase> columns { get; } = new ObservableCollection<ColumnBase>(); public ObservableCollection<ColumnBase> columns { get; } = new ObservableCollection<ColumnBase>();
public Row current_row { get => _current_row.Value; set => _current_row.set(value); }
public SecurityImmutable? current_security => current_row?.security;
public SecurityMD? current_security_md => current_row?.security_md;
public SimpleGridSettingsManager<Row> grid_settings_manager { get; } internal IBus bus => _bus;
internal OrdersModel orders_model => _orders_model;
public GridSettings get_grid_save_state() { public IDataGridColumnPersistentFilter<Row, string> security_filter { get; }
if (_settings_manager.instance_settings == null) public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> bid_price_filter { get; } = new DoubleMinMax<Row>(r => r.bid_price, nameof(Row.bid_price));
return null; public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> bid_merged_size_filter { get; } = new UIntMinMax<Row>(r => r.bid_merged_size, nameof(Row.bid_merged_size));
else public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> bid_direct_size_filter { get; } = new UIntMinMax<Row>(r => r.bid_direct_size, nameof(Row.bid_direct_size));
return grid_settings_manager.create(); public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> bid_implied_size_filter { get; } = new UIntMinMax<Row>(r => r.bid_implied_size, nameof(Row.bid_implied_size));
} public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> ask_price_filter { get; } = new DoubleMinMax<Row>(r => r.ask_price, nameof(Row.ask_price));
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> ask_merged_size_filter { get; } = new UIntMinMax<Row>(r => r.ask_merged_size, nameof(Row.ask_merged_size));
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> ask_direct_size_filter { get; } = new UIntMinMax<Row>(r => r.ask_direct_size, nameof(Row.ask_direct_size));
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> ask_implied_size_filter { get; } = new UIntMinMax<Row>(r => r.ask_implied_size, nameof(Row.ask_implied_size));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> last_price_filter { get; } = new DoubleMinMax<Row>(r => r.last_price, nameof(Row.last_price));
public IDataGridColumnPersistentFilter<Row, string> last_price_from_spread_filter { get; } = new RegexFilterVM<Row>(r => r.last_price_from_spread.ToString(), nameof(Row.last_price_from_spread));
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> last_size_filter { get; } = new UIntMinMax<Row>(r => r.last_size, nameof(Row.last_size));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> day_change_filter { get; } = new DoubleMinMax<Row>(r => r.day_change, nameof(Row.day_change));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> settlement_filter { get; } = new DoubleMinMax<Row>(r => r.settlement, nameof(Row.settlement));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> session_low_filter { get; } = new DoubleMinMax<Row>(r => r.session_low, nameof(Row.session_low));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> session_high_filter { get; } = new DoubleMinMax<Row>(r => r.session_high, nameof(Row.session_high));
public IDataGridColumnPersistentFilter<Row, IntMinMaxState> day_position_filter { get; } = new IntMinMax<Row>(r => unchecked((int)r.day_position), nameof(Row.day_position));
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> raw_day_position_filter { get; } = new DoubleMinMax<Row>(r => r.raw_day_position, nameof(Row.raw_day_position));
public IDataGridColumnPersistentFilter<Row, IntMinMaxState> working_bid_volume_filter { get; } = new IntMinMax<Row>(r => r.working_bid_volume, nameof(Row.working_bid_volume));
public IDataGridColumnPersistentFilter<Row, IntMinMaxState> working_ask_volume_filter { get; } = new IntMinMax<Row>(r => r.working_ask_volume, nameof(Row.working_ask_volume));
public IDataGridColumnPersistentFilter<Row, ULongMinMaxState> volume_filter { get; } = new ULongMinMax<Row>(r => r.volume, nameof(Row.volume));
public IDataGridColumnPersistentFilter<Row, string> security_key_filter { get; } = new RegexFilterVM<Row>(r => r.security_key.ToString(), nameof(Row.security_key));
public IDataGridColumnPersistentFilter<Row, string> market_description_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.MarketDescription : "", nameof(Row.market_description));
public IDataGridColumnPersistentFilter<Row, string> cleared_alias_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.ClearedAlias : "", nameof(Row.cleared_alias));
public IDataGridColumnPersistentFilter<Row, string> product_description_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.ProductName : "", nameof(Row.product_description));
public IDataGridColumnPersistentFilter<Row, string> hub_alias_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.HubAlias : "", nameof(Row.hub_alias));
public IDataGridColumnPersistentFilter<Row, string> strip_name_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.StripName : "", nameof(Row.strip_name));
public IDataGridColumnPersistentFilter<Row, string> mic_code_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.MicCode : "", nameof(Row.mic_code));
IEnumerable<IDataGridColumnFilter<Row>> _all_filters =>
_filter_getters.Select(g => g(this));
public static IComparer<Row> get_column_comparer(Columns column) { public static IComparer<Row> get_column_comparer(Columns column) {
switch (column) { switch (column) {
@@ -181,8 +373,9 @@ namespace mbts.spark {
case Columns.SecurityKey: return wrap(r => r.security.Id); case Columns.SecurityKey: return wrap(r => r.security.Id);
case Columns.Volume: return wrap(r => r.volume); case Columns.Volume: return wrap(r => r.volume);
case Columns.Last: return wrap(r => r.last_price); case Columns.Last: return wrap(r => r.last_price);
case Columns.LastSpd: return wrap(r => r.last_price_from_spread);
case Columns.LastSize: return wrap(r => r.last_size); case Columns.LastSize: return wrap(r => r.last_size);
case Columns.Position: return wrap(r => r.position); case Columns.Position: return wrap(r => r.day_position);
case Columns.WorkingBids: return wrap(r => r.working_bid_volume); case Columns.WorkingBids: return wrap(r => r.working_bid_volume);
case Columns.BidImpliedSize: return wrap(r => r.bid_implied_size); case Columns.BidImpliedSize: return wrap(r => r.bid_implied_size);
case Columns.BidDirectSize: return wrap(r => r.bid_direct_size); case Columns.BidDirectSize: return wrap(r => r.bid_direct_size);
@@ -209,37 +402,60 @@ namespace mbts.spark {
Comparer<T>.Default.wrap(selector); Comparer<T>.Default.wrap(selector);
} }
#region Filters public IComparer<Row> comparer {
public IDataGridColumnPersistentFilter<Row, string> security_filter { get; } get => _comparer;
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> bid_price_filter { get; } = new DoubleMinMax<Row>(r => r.bid_price, nameof(Row.bid_price)); set => _rows_view.CustomSort = (_comparer = value)?.to_non_generic();
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> bid_merged_size_filter { get; } = new UIntMinMax<Row>(r => r.bid_merged_size, nameof(Row.bid_merged_size)); }
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> bid_direct_size_filter { get; } = new UIntMinMax<Row>(r => r.bid_direct_size, nameof(Row.bid_direct_size));
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> bid_implied_size_filter { get; } = new UIntMinMax<Row>(r => r.bid_implied_size, nameof(Row.bid_implied_size)); public (FillsVM vm, string context, string title, Color fg) fills_params(IEnumerable<SecurityImmutable> securities, Columns column) {
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> ask_price_filter { get; } = new DoubleMinMax<Row>(r => r.ask_price, nameof(Row.ask_price)); var (title_desc, fg) = _fills_title(column);
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> ask_merged_size_filter { get; } = new UIntMinMax<Row>(r => r.ask_merged_size, nameof(Row.ask_merged_size)); var state = StartupData.DefaultAuxiliaryFills;
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> ask_direct_size_filter { get; } = new UIntMinMax<Row>(r => r.ask_direct_size, nameof(Row.ask_direct_size)); if (state.filters == null)
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> ask_implied_size_filter { get; } = new UIntMinMax<Row>(r => r.ask_implied_size, nameof(Row.ask_implied_size)); state.filters = new bts.shell.fills.FillsFilterStates();
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> last_price_filter { get; } = new DoubleMinMax<Row>(r => r.last_price, nameof(Row.last_price)); switch (column) {
public IDataGridColumnPersistentFilter<Row, string> last_price_from_spread_filter { get; } = new RegexFilterVM<Row>(r => r.last_price_from_spread.ToString(), nameof(Row.last_price_from_spread)); case Columns.RawDayPosition:
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> last_size_filter { get; } = new UIntMinMax<Row>(r => r.last_size, nameof(Row.last_size)); state.filters.fill_kind = new[] {
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> day_change_filter { get; } = new DoubleMinMax<Row>(r => r.day_change, nameof(Row.day_change)); Fill.Types.FillKind.Standard
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> settlement_filter { get; } = new DoubleMinMax<Row>(r => r.settlement, nameof(Row.settlement)); };
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> session_low_filter { get; } = new DoubleMinMax<Row>(r => r.session_low, nameof(Row.session_low)); break;
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> session_high_filter { get; } = new DoubleMinMax<Row>(r => r.session_high, nameof(Row.session_high)); case Columns.Position:
public IDataGridColumnPersistentFilter<Row, IntMinMaxState> position_filter { get; } = new IntMinMax<Row>(r => r.position, nameof(Row.position)); state.filters.fill_kind = new[] {
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> raw_day_position_filter { get; } = new DoubleMinMax<Row>(r => r.raw_day_position, nameof(Row.raw_day_position)); Fill.Types.FillKind.Standard,
public IDataGridColumnPersistentFilter<Row, IntMinMaxState> working_bid_volume_filter { get; } = new IntMinMax<Row>(r => r.working_bid_volume, nameof(Row.working_bid_volume)); Fill.Types.FillKind.Sod
public IDataGridColumnPersistentFilter<Row, IntMinMaxState> working_ask_volume_filter { get; } = new IntMinMax<Row>(r => r.working_ask_volume, nameof(Row.working_ask_volume)); };
public IDataGridColumnPersistentFilter<Row, ULongMinMaxState> volume_filter { get; } = new ULongMinMax<Row>(r => r.volume, nameof(Row.volume)); break;
public IDataGridColumnPersistentFilter<Row, string> security_key_filter { get; } = new RegexFilterVM<Row>(r => r.security_key.ToString(), nameof(Row.security_key)); }
state.grid = GridSettingsHelper.hide_cols(state.grid, new[] { ui.spark.FillsView.Columns.Security });
public IDataGridColumnPersistentFilter<Row, string> market_description_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.MarketDescription : "", nameof(Row.market_description)); var sec_keys = securities.Select(SecurityDataHelper.key_fn);
public IDataGridColumnPersistentFilter<Row, string> cleared_alias_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.ClearedAlias : "", nameof(Row.cleared_alias)); if (securities.All(s => s.ContractCase == Security.ContractOneofCase.Synthetic)) {
public IDataGridColumnPersistentFilter<Row, string> product_description_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.ProductName : "", nameof(Row.product_description)); state.root_securities = sec_keys.ToArray();
public IDataGridColumnPersistentFilter<Row, string> hub_alias_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.HubAlias : "", nameof(Row.hub_alias)); } else {
public IDataGridColumnPersistentFilter<Row, string> strip_name_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.StripName : "", nameof(Row.strip_name)); state.filters.security = SecurityCriteria.from_keys(sec_keys);
public IDataGridColumnPersistentFilter<Row, string> mic_code_filter { get; } = new RegexFilterVM<Row>(r => r.security.HasIce ? r.security.Ice.MicCode : "", nameof(Row.mic_code)); }
var vm = new FillsVM(
_bus, _orders_model, Observable.Return(state), new WindowSettingsManager<GridSettings>.DisconnectedImpl(state.grid));
return (vm, $"{string.Join(_security_delimiter, securities)}", title_desc, fg);
}
public (OrderBookVM vm, string context, string title, Color fg) orderbook_params(IEnumerable<SecurityImmutable> securities, Columns column) {
var (title_desc, fg) = _orderbook_title(column);
var filters = new bts.shell.orderbook.FilterStates {
security_criteria = SecurityCriteria.from_keys(securities.Select(SecurityDataHelper.key_fn)),
order_types = securities.All(s => s.ContractCase == Security.ContractOneofCase.Synthetic) ?
new[] { new AlgoID(CustomOrderDefinition.CustomOneofCase.Spreader) } :
AlgoID.exchange_algo_keys,
statuses = new[] { OrderStatus.Working }
};
switch (column) {
case Columns.WorkingBids: filters.sides = new[] { Side.Buy }; break;
case Columns.WorkingAsks: filters.sides = new[] { Side.Sell }; break;
}
var vm = _mk_orderbook_vm_common(filters, new[] {
OrderBookGridView.ColumnKeys.Security,
OrderBookGridView.ColumnKeys.Side
});
return (vm, $"{string.Join(_security_delimiter, securities)}", title_desc, fg);
}
public FilterStates get_filter_states() { public FilterStates get_filter_states() {
return new FilterStates { return new FilterStates {
@@ -259,7 +475,7 @@ namespace mbts.spark {
settlement = settlement_filter.get_state(), settlement = settlement_filter.get_state(),
session_low = session_low_filter.get_state(), session_low = session_low_filter.get_state(),
session_high = session_high_filter.get_state(), session_high = session_high_filter.get_state(),
position = position_filter.get_state(), day_position = day_position_filter.get_state(),
raw_day_position = raw_day_position_filter.get_state(), raw_day_position = raw_day_position_filter.get_state(),
working_bid_volume = working_bid_volume_filter.get_state(), working_bid_volume = working_bid_volume_filter.get_state(),
working_ask_volume = working_ask_volume_filter.get_state(), working_ask_volume = working_ask_volume_filter.get_state(),
@@ -273,14 +489,109 @@ namespace mbts.spark {
mic_code = mic_code_filter.get_state(), mic_code = mic_code_filter.get_state(),
}; };
} }
#endregion
protected override Row row_factory(SecurityMD smd) => new Row(_bus, smd, _orders_model); public void load_filters(FilterStates filters) {
protected override void on_row_removed(Row row) => row.Dispose(); if (filters != null) {
protected override IEnumerable<SortingCriteria> get_default_sorting() { yield return new SortingCriteria(nameof(Row.security), true); } using (rows_view.DeferRefresh()) {
security_filter.load_state(filters.security);
bid_price_filter.load_state(filters.bid_price);
bid_merged_size_filter.load_state(filters.bid_merged_size);
bid_direct_size_filter.load_state(filters.bid_direct_size);
bid_implied_size_filter.load_state(filters.bid_implied_size);
ask_price_filter.load_state(filters.ask_price);
ask_merged_size_filter.load_state(filters.ask_merged_size);
ask_direct_size_filter.load_state(filters.ask_direct_size);
ask_implied_size_filter.load_state(filters.ask_implied_size);
last_price_filter.load_state(filters.last_price);
last_price_from_spread_filter.load_state(filters.last_price_from_spread);
last_size_filter.load_state(filters.last_size);
day_change_filter.load_state(filters.day_change);
settlement_filter.load_state(filters.settlement);
session_low_filter.load_state(filters.session_low);
session_high_filter.load_state(filters.session_high);
day_position_filter.load_state(filters.day_position);
raw_day_position_filter.load_state(filters.raw_day_position);
working_bid_volume_filter.load_state(filters.working_bid_volume);
working_ask_volume_filter.load_state(filters.working_ask_volume);
volume_filter.load_state(filters.volume);
security_key_filter.load_state(filters.security_key);
}
}
}
static (string desc, Color fg) _fills_title(Columns key) {
switch (key) {
case Columns.Position: return ("Day Fills", Colors.Black);
case Columns.RawDayPosition: return ("Raw Day Fills", Colors.Black);
default: return ("Fills", Colors.Black);
}
}
static (string desc, Color fg) _orderbook_title(Columns key) {
switch (key) {
case Columns.WorkingBids: return ("Working Buy Orders", BTSColors.MarketData.bid);
case Columns.WorkingAsks: return ("Working Sell Orders", BTSColors.MarketData.ask);
default: return ("Working Orders", Colors.Black);
}
}
static GridSettings _hide_cols(GridSettings grid, IEnumerable<OrderBookGridView.ColumnKeys> columns) =>
grid.with(_hide_cols(grid.columns, columns));
static IEnumerable<GridColumnSettings> _hide_cols(IEnumerable<GridColumnSettings> cols, IEnumerable<OrderBookGridView.ColumnKeys> columns) {
// hide columns who's data is implied by the grouping
var col_hash = new HashSet<string>(columns.Select(k => k.ToString()));
foreach (var c in cols)
yield return col_hash.Contains(c.id) ? c.with(is_visible: false) : c;
}
static string _order_ticket_tooltip(Columns key) {
var bid_or_ask = Regex.Match(key.ToString(), "(Bid|Ask)");
return bid_or_ask.Success ? $"Order Ticket @ {bid_or_ask.Value}" : "Order Ticket";
}
OrderBookVM _mk_orderbook_vm_common(bts.shell.orderbook.FilterStates filters, IEnumerable<OrderBookGridView.ColumnKeys> hide_cols, IObservable<TableUpdate<OrderSecurityRootPair, uint>> orders_source = null) {
var state = new bts.shell.orderbook.OrderBookStartupData(filters, bts.shell.orderbook.OrderBookStartupData.default_mini_grid, use_defaults: false);
state.orderbook_grid.general = _hide_cols(state.orderbook_grid.general, hide_cols);
var settings_man = new WindowSettingsManager<bts.shell.orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
var obvm = orders_source == null ?
new OrderBookVM(_bus, null, _orders_model, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, orders_source, settings_man, true);
foreach (var c in OrderBookVM.OrderBookColumnCollection.editable_columns)
obvm.columns.Insert(0, c);
obvm.load_from(state);
return obvm;
}
void _refresh() { void _refresh() {
foreach (var r in _row_vms) r.refresh(); foreach (var r in _rows) {
r.refresh();
r.is_visible = _filter == null || _filter(r);
}
}
Row _row_factory(SecurityMD smd) => new Row(_bus, smd, _orders_model);
void IHandleRowSelection.row_selection_changed(SelectionChangedEventArgs e) {
selected_rows.RemoveSorted(e.RemovedItems.OfType<Row>(), _row_key_comparer);
selected_rows.InsertSorted(e.AddedItems.OfType<Row>(), _row_key_comparer);
}
void _on_securities(TableUpdate<SecurityMD, uint> table) {
var sw = new Stopwatch();
sw.Start();
foreach (var smd in table.removed) {
int i = CollectionHelper.binary_search(_wrapped_rows, smd, _sec_md_key_comparer);
Log.assert(i >= 0);
_wrapped_rows.RemoveAt(i);
}
foreach (var smd in table.added) {
int i = CollectionHelper.binary_search(_wrapped_rows, smd, _sec_md_key_comparer);
Log.assert(i < 0);
_wrapped_rows.Insert(~i, smd);
}
sw.Stop();
Log.Ui.info($"MarketView update took {sw.ElapsedMilliseconds:0.00}ms.");
} }
} }
} }
@@ -3,8 +3,12 @@
x:ClassModifier="internal" x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:bv="clr-namespace:bts.view"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls" xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:usp="clr-namespace:mbts.ui.spark" xmlns:usp="clr-namespace:mbts.ui.spark"
u:WindowStyle.UnsafeWindow="{Binding Path='(u:WindowStyle.UnsafeWindow)', RelativeSource={RelativeSource AncestorType=bv:SparkWindowView}}"
FocusManager.IsFocusScope="True" FocusManager.IsFocusScope="True"
Background="{StaticResource CommonBackground}" Background="{StaticResource CommonBackground}"
> >
@@ -13,8 +17,56 @@
<ResourceDictionary.MergedDictionaries> <ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/FilterTemplates.xaml"/> <ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/FilterTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries> </ResourceDictionary.MergedDictionaries>
<Style TargetType="c:HyperlinkCell">
<Setter Property="Background" Value="{Binding Path='(c:DIYGrid.Column).background_brush', RelativeSource={RelativeSource Self}}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Command" Value="{x:Static usp:MarketViewView.CellClickCommand}"/>
<Setter Property="CommandParameter">
<Setter.Value>
<MultiBinding Converter="{x:Static usp:MarketViewView.CellConverter}">
<Binding Path=""/>
<Binding Path="(c:DIYGrid.ColumnKey)" RelativeSource="{RelativeSource Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
<Setter Property="CommandTarget" Value="{Binding RelativeSource={RelativeSource AncestorType=usp:MarketViewView}}"/>
<Style.Triggers>
<Trigger Property="IsMouseOverClickArea" Value="True">
<Setter Property="Background">
<Setter.Value>
<MultiBinding>
<MultiBinding.Converter>
<cv:MultiValueConverterPipe>
<cv:ColorBlendMultiConverter/>
<cv:ColorToBrushConverter/>
</cv:MultiValueConverterPipe>
</MultiBinding.Converter>
<Binding Path="(c:DIYGrid.Grid).SelectionHighlight" RelativeSource="{RelativeSource Self}"/>
<Binding Path="(c:DIYGrid.Column).background_color" RelativeSource="{RelativeSource Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
<Setter Property="BorderBrush">
<Setter.Value>
<Binding Path="SelectionHighlight" RelativeSource="{RelativeSource AncestorType=c:DIYGrid}">
<Binding.Converter>
<cv:ValueConverterPipe>
<cv:ColorWithConverter A="255"/>
<cv:ColorToBrushConverter/>
</cv:ValueConverterPipe>
</Binding.Converter>
</Binding>
</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="1"/>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary> </ResourceDictionary>
</UserControl.Resources> </UserControl.Resources>
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static usp:MarketViewView.CellClickCommand}" Executed="{x:Static usp:MarketViewView.CellClickExecuted}"/>
</UserControl.CommandBindings>
<AdornerDecorator> <AdornerDecorator>
<Grid> <Grid>
<Grid.RowDefinitions> <Grid.RowDefinitions>
@@ -22,13 +74,14 @@
<RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<c:DIYGrid <c:DIYGrid
x:Name="_grid" x:Name="_grid"
Grid.Row="0" Grid.Row="0"
Columns="{Binding columns}" Columns="{Binding columns}"
CurrentRow="{Binding current_row}" CurrentRow="{Binding current_row}"
Rows="{Binding rows_view}" Rows="{Binding rows_view}"
SelectionHighlight="{Binding grid_settings_manager.selection_highlight, Mode=OneWay}" SelectionHighlight="{Binding selection_highlight, Mode=OneWay}"
> SyncColumnSortDirectionWithSortDescriptions="False"
>
<c:DIYGrid.InputBindings> <c:DIYGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/> <MouseBinding MouseAction="LeftDoubleClick" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
<KeyBinding Key="Return" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/> <KeyBinding Key="Return" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
@@ -1,14 +1,37 @@
using mbts.spark; using bts.api;
using mbts.spark;
using mbts.ui.controls; using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.extensions;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace mbts.ui.spark { namespace mbts.ui.spark {
/// <summary> /// <summary>
/// Interaction logic for MarketSheetsView.xaml /// Interaction logic for MarketSheetsView.xaml
/// </summary> /// </summary>
partial class MarketViewView : UserControl { partial class MarketViewView : UserControl {
public static readonly RoutedCommand CellClickCommand = new RoutedCommand();
MarketViewVM _vm;
DIYGridPopupManager _popup_man_backing;
public MarketViewView() {
InitializeComponent();
this.ConnectDataContext<MarketViewVM>(vm => _vm = vm);
AdornerHelper.attach_continuously_on_loaded(
() => new GridAnimation.DIYGridAnimationAdorner<Columns>(
_grid, _grid.descendants_of_type<DIYGridRowsPresenter>().First()),
_grid);
}
public enum Columns { public enum Columns {
None,
Security, Security,
Volume, Volume,
Last, Last,
@@ -39,14 +62,116 @@ namespace mbts.ui.spark {
MicCode MicCode
} }
public MarketViewView() { public static ExecutedRoutedEventHandler
InitializeComponent(); CellClickExecuted => CommandImpl.cell_click;
AdornerHelper.attach_continuously_on_loaded(
() => new GridAnimation.DIYGridAnimationAdorner<Columns>( public static IMultiValueConverter CellConverter =>
_grid, _grid.descendants_of_type<DIYGridRowsPresenter>().First()), ValueConverter.create<MarketViewVM.Row, Columns, MarketViewCell>((r, c) => new MarketViewCell(r, c));
_grid);
IBus _bus => _vm.bus;
OrdersModel _model => _vm.orders_model;
DIYGridPopupManager _popup_man =>
_popup_man_backing ?? (_popup_man_backing = DIYGridPopupManager.create(this));
public void show_working_orders(IReadOnlyList<SecurityImmutable> securities) =>
_show_mini_orderbook(securities, Columns.None);
public void show_mini_fills(IReadOnlyList<SecurityImmutable> securities) =>
_show_mini_fills(securities, Columns.None);
public void show_order_ticket(SecurityMD security_md) =>
_show_order_ticket(security_md);
void _on_cell_click(MarketViewVM.Row row, Columns col) {
switch (col) {
case Columns.WorkingAsks:
case Columns.WorkingBids:
_show_mini_orderbook(row.security, col);
break;
case Columns.Bid:
_show_order_ticket(row.security_md, row.bid_price);
break;
case Columns.BidMergedSize: _show_order_ticket(row.security_md, row.bid_price, row.bid_merged_size); break;
case Columns.BidDirectSize: _show_order_ticket(row.security_md, row.bid_price, row.bid_direct_size); break;
case Columns.BidImpliedSize: _show_order_ticket(row.security_md, row.bid_price, row.bid_implied_size); break;
case Columns.Ask:
_show_order_ticket(row.security_md, row.ask_price);
break;
case Columns.AskMergedSize: _show_order_ticket(row.security_md, row.ask_price, row.ask_merged_size); break;
case Columns.AskDirectSize: _show_order_ticket(row.security_md, row.ask_price, row.ask_direct_size); break;
case Columns.AskImpliedSize: _show_order_ticket(row.security_md, row.ask_price, row.ask_implied_size); break;
case Columns.Last:
_show_order_ticket(row.security_md, row.last_price);
break;
case Columns.LastSize:
_show_order_ticket(row.security_md, row.last_price, row.last_size);
break;
case Columns.Position:
case Columns.RawDayPosition:
_show_mini_fills(row.security, col);
break;
}
}
void _show_mini_orderbook(SecurityImmutable security, Columns col) =>
_show_mini_orderbook(new[] { security }, col);
void _show_mini_orderbook(IReadOnlyList<SecurityImmutable> securities, Columns col) {
var (vm, context, title, fg) = _vm.orderbook_params(securities, col);
_show_popup(vm, new AuxiliaryDataHeader {
context = context,
title = title,
title_foreground = fg
});
}
void _show_mini_fills(SecurityImmutable security, Columns col) =>
_show_mini_fills(new[] { security }, col);
void _show_mini_fills(IEnumerable<SecurityImmutable> securities, Columns col) {
var (vm, context, title, fg) = _vm.fills_params(securities, col);
_show_popup(vm, new AuxiliaryDataHeader {
context = context,
title = title,
title_foreground = fg
});
}
void _show_order_ticket(SecurityMD security_md, double price = double.NaN, uint size = 0) {
var resources = new OrderTicketResources();
resources.MergedDictionaries.Add(new AuxiliaryDataResources());
var ticket_vm = new NewOrderTicketVM(
_model, security_md, _model.factory.order(security_md.security), price, size, Observable.Return(mbts.spark.LadderSettings.Default.calculator_buttons));
_show_popup(ticket_vm, new OrderTicketHeader { bbo = ticket_vm.bbo }, resources);
}
void _show_popup(object content, object header) {
var resources = new AuxiliaryDataResources();
resources.MergedDictionaries.Add(new AutoHideScrollbarResources());
_show_popup(content, header, resources);
}
void _show_popup(object content, object header, ResourceDictionary resources) {
var view = new HeaderedContentControl {
DataContext = content,
Content = content,
Header = header,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Resources = resources ?? new AuxiliaryDataResources()
};
view.Style = view.Resources[AuxiliaryDataResources.PopupChildStyleKey] as Style;
_popup_man.show_async(view).ignore();
}
static class CommandImpl {
public static void cell_click(object sender, ExecutedRoutedEventArgs e) {
if (sender is MarketViewView mview && e.Parameter is MarketViewCell cell)
mview._on_cell_click(cell.row, cell.column);
e.Handled = true;
}
} }
} }
class MarketViewRowView : DIYGrid.HighPerformanceRow<MarketViewVM.Row, MarketViewView.Columns> { } class MarketViewRowView : DIYGrid.HighPerformanceRow<MarketViewVM.Row> { }
} }
@@ -1,18 +1,21 @@
using bts; using bts;
using bts.api; using bts.api;
using bts.api.core;
using bts.collections;
using bts.shell; using bts.shell;
using bts.shell.fills; using bts.shell.fills;
using bts.spark; using bts.spark;
using bts.utils;
using mbts.persist; using mbts.persist;
using mbts.ui; using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings; using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.spark; using mbts.ui.spark;
using mbts.ui.utility; using mbts.ui.utility;
using mbts.utils; using mbts.utils;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Reactive.Disposables; using System.Reactive.Disposables;
using System.Reactive.Linq; using System.Reactive.Linq;
@@ -21,9 +24,18 @@ using System.Windows;
namespace mbts.spark { namespace mbts.spark {
class MarketViewWindow : SparkWindow<MarketViewWindowFactory.StartupData>, ISharedWindow, ISlowMeasureContentSize { class MarketViewWindow : SparkWindow<MarketViewWindowFactory.StartupData>, ISharedWindow, ISlowMeasureContentSize {
const string _window_type = "MarketView", _window_type_display_name = "Market View"; const string _window_type = "MarketView", _window_type_display_name = "Market View";
// make font-color immutable for Side, Size, (the font-color rule is hard-coded: MarketData.bid for Buy orders, MarketData.ask for Sells)
static readonly IReadOnlyDictionary<string, GridColumnSettingsFeatureFlags> _col_settings_flags = new Dictionary<string, GridColumnSettingsFeatureFlags> {
{ MarketViewView.Columns.Bid.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor | GridColumnSettingsFeatureFlags.ImmutableBackgroundColor },
{ MarketViewView.Columns.Ask.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor | GridColumnSettingsFeatureFlags.ImmutableBackgroundColor},
{ MarketViewView.Columns.WorkingAsks.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor },
{ MarketViewView.Columns.WorkingBids.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }
};
readonly OrdersModel _orders_model; readonly OrdersModel _orders_model;
readonly AllowOnce _init_guard = new AllowOnce("MarketView"); readonly AllowOnce _init_guard = new AllowOnce("MarketView");
readonly IWindowSettingsManager<GridSettings> _settings_manager; readonly IWindowSettingsManager<GridSettings> _settings_manager;
List<SortingCriteria> _current_sorting_criterion;
MarketViewVM _vm; MarketViewVM _vm;
MarketViewView _view; MarketViewView _view;
MarketViewWindowFactory.StartupData _state; MarketViewWindowFactory.StartupData _state;
@@ -32,6 +44,7 @@ namespace mbts.spark {
SecurityCriteria SecurityCriteria
_selected_security_criteria_backing, _selected_security_criteria_backing,
_sorted_selected_security_criteria_backing; _sorted_selected_security_criteria_backing;
SimpleGridSettingsManager<MarketViewVM.Row> _grid_settings_manager;
public MarketViewWindow(MarketViewWindowFactory factory, IBus bus, OrdersModel orders_model, MarketViewWindowFactory.StartupData state, IWindowSettingsManager<GridSettings> settings_manager) public MarketViewWindow(MarketViewWindowFactory factory, IBus bus, OrdersModel orders_model, MarketViewWindowFactory.StartupData state, IWindowSettingsManager<GridSettings> settings_manager)
: base("Market View", bus, factory, SparkCommands.ShowMarketView.icon) { : base("Market View", bus, factory, SparkCommands.ShowMarketView.icon) {
@@ -42,13 +55,17 @@ namespace mbts.spark {
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().market_view ? "MarketView" : null; thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().market_view ? "MarketView" : null;
} }
event Action<MarketViewWindowFactory.StartupData> _state_changed; event Action<SecurityCriteria> _security_criteria_changed;
public override string window_type => _window_type; public override string window_type => _window_type;
public override UIElement Content => _view; public override UIElement Content => _view;
public override IEnumerable<SparkCommand> Commands => _commands; public override IEnumerable<SparkCommand> Commands => _commands;
public override MarketViewWindowFactory.StartupData SaveState => public override MarketViewWindowFactory.StartupData SaveState =>
_state = new MarketViewWindowFactory.StartupData(_state.security_criteria, _vm.get_filter_states(), _vm.get_grid_save_state(), _vm.rows_view.get_sorting_criteria(_vm.columns)); _state = new MarketViewWindowFactory.StartupData(
_state.security_criteria,
_vm.get_filter_states(),
_settings_manager.instance_settings,
_current_sorting_criterion);
public override double MinWidth => MarketViewWindowFactory.StartupData.DefaultGridSettings.columns.Where(c => c.is_visible).Sum(gcs => gcs.width) public override double MinWidth => MarketViewWindowFactory.StartupData.DefaultGridSettings.columns.Where(c => c.is_visible).Sum(gcs => gcs.width)
+ SPARK_MENU_COLLAPSED_WIDTH + SPARK_MENU_COLLAPSED_WIDTH
@@ -68,43 +85,47 @@ namespace mbts.spark {
return _selected_security_criteria_backing; return _selected_security_criteria_backing;
} }
} }
SecurityCriteria _sorted_selected_security_criteria {
get { SecurityCriteria _sorted_selected_security_criteria => _sorted_selected_security_criteria_backing ?? (
if (_sorted_selected_security_criteria_backing == null) { _sorted_selected_security_criteria_backing = _vm != null ?
if (_vm != null) { new SecurityCriteria(_vm.selected_rows.Ordered(_vm.comparer).Select(r => r.security)) :
var sorting_criteria = _vm.rows_view.get_sorting_criteria(_vm.columns); null);
var comp_builder = new ComparerBuilder<MarketViewVM.Row>();
foreach (var sc in sorting_criteria) {
if (_vm.columns.TryGetFirst(col => string.Equals(col.id, sc.col_name, StringComparison.CurrentCultureIgnoreCase), out var match)) {
if (match is ui.controls.DIYGrid.IKeyedColumn<MarketViewView.Columns> kcol) {
var col_comp = MarketViewVM.get_column_comparer(kcol.key);
if (col_comp != null) {
comp_builder.add(sc.is_ascending ? col_comp : col_comp.reverse());
} else {
Log.Ui.warn($"{_window_type} is unable to find the row comparer for the '{sc.col_name}' column.");
}
} else {
Log.Ui.warn($"{_window_type} is unable find a column with id '{sc.col_name}.'");
}
}
}
var comp = comp_builder.to_comparer();
_sorted_selected_security_criteria_backing = new SecurityCriteria(_vm.selected_rows.Ordered(comp).Select(r => r.security));
}
}
return _sorted_selected_security_criteria_backing;
}
}
bool _has_selected_rows() => _vm != null && _vm.selected_rows.Count > 0; bool _has_selected_rows() => _vm != null && _vm.selected_rows.Count > 0;
public void thread_init() { public void thread_init() {
_init_guard.check_access(); _init_guard.check_access();
Log.notnull(_state); Log.notnull(_state);
var state_src = Observable.FromEvent<Action<MarketViewWindowFactory.StartupData>, MarketViewWindowFactory.StartupData>(cb => _state_changed += cb, cb => _state_changed -= cb).StartWith(_state); var update_securities_cmd = SparkCommands.change_securities_callback(_window_type_display_name);
_vm = new MarketViewVM(_bus, _orders_model, state_src, _settings_manager); var security_md_map_src = Observable.Create<IReadOnlyDictionary<uint, SecurityMD>>(o => {
IDisposable sub = null;
_security_criteria_changed += on_security_criteria_changed;
on_security_criteria_changed(_state.security_criteria);
return Disposable.Create(dispose);
void on_security_criteria_changed(SecurityCriteria security_criteria) {
sub?.Dispose();
sub = _state.security_criteria.subscribe_md_map(_bus).Subscribe(o.OnNext);
}
void dispose() =>
Disposable.dispose(ref sub);
});
_vm = new MarketViewVM(
_bus,
_orders_model,
security_md_map_src
.BufferLatest(TimeSpan.FromSeconds(1))
.Table(SecurityMD.key_fn)
.Where(t => t.has_changes())
.OnDispatcher());
var sort_man = new ColumnSortManager(_vm.columns, MarketViewView.Columns.Security.ToString());
_current_sorting_criterion = _state.sorting_criterion.ToList();
sort_man.load(_state.sorting_criterion);
_vm.load_filters(_state.filters);
_vm.comparer = sort_man.build_comparer<MarketViewView.Columns, MarketViewVM.Row>(MarketViewVM.get_column_comparer);
_view = new MarketViewView { DataContext = _vm }; _view = new MarketViewView { DataContext = _vm };
_view._grid.Sorting += on_grid_sorting; _view._grid.Sorting += on_grid_sorting;
_grid_settings_manager = new SimpleGridSettingsManager<MarketViewVM.Row>(_vm.columns, _col_settings_flags, _vm.rows);
_grid_settings_manager.load_from(_settings_manager.current_settings());
/// The 'CanExecute' plumbing for the cmds below is designed to avoid potentially costly .ToList() operations on the selected_rows/securities. /// The 'CanExecute' plumbing for the cmds below is designed to avoid potentially costly .ToList() operations on the selected_rows/securities.
/// Some of the cmds post ITags with data that is, or has, a SecurityCriteria member; the SecurityCriteria constructor creates a new List of the specified securities. /// Some of the cmds post ITags with data that is, or has, a SecurityCriteria member; the SecurityCriteria constructor creates a new List of the specified securities.
/// For these commands, the objective is to evaluate 'CanExecute' without instantiating the SecurityCriteria (or more importantly, without creating a new List). /// For these commands, the objective is to evaluate 'CanExecute' without instantiating the SecurityCriteria (or more importantly, without creating a new List).
@@ -126,6 +147,13 @@ namespace mbts.spark {
}); });
var show_fills_actual_cmd = SparkCommands.ShowFills(); var show_fills_actual_cmd = SparkCommands.ShowFills();
var show_fills_cmd_wrapper = new SparkCommandCommand(show_fills_actual_cmd.title, show_fills_actual_cmd.icon, show_fills_cmd, SparkCommands.KeyGestures.ShowFills); var show_fills_cmd_wrapper = new SparkCommandCommand(show_fills_actual_cmd.title, show_fills_actual_cmd.icon, show_fills_cmd, SparkCommands.KeyGestures.ShowFills);
var show_mini_fills_cmd = new DelegateCommand(() => _view.show_mini_fills(_vm.selected_securities), () => _vm.selected_securities.Count > 0);
var show_ticket_cmd = new DelegateCommand(() => {
var smd = _vm.current_security_md;
if (smd.HasValue)
_view.show_order_ticket(smd.Value);
}, () => _vm.current_security_md.HasValue);
var show_ticket_actual_cmd = SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket);
// show synthetic create // show synthetic create
var show_synth_create_cmd = new DelegateCommand(() => { var show_synth_create_cmd = new DelegateCommand(() => {
var sc = _sorted_selected_security_criteria; var sc = _sorted_selected_security_criteria;
@@ -134,15 +162,29 @@ namespace mbts.spark {
}, () => _vm.selected_rows.Count > 0 && _vm.selected_rows.Count <= 24); }, () => _vm.selected_rows.Count > 0 && _vm.selected_rows.Count <= 24);
var show_synth_create_actual_cmd = SparkCommands.ShowSyntheticCreate(); var show_synth_create_actual_cmd = SparkCommands.ShowSyntheticCreate();
var show_synth_create_cmd_wrapper = new SparkCommandCommand(show_synth_create_actual_cmd.title, show_synth_create_actual_cmd.icon, show_synth_create_cmd, SparkCommands.KeyGestures.ShowSyntheticCreate); var show_synth_create_cmd_wrapper = new SparkCommandCommand(show_synth_create_actual_cmd.title, show_synth_create_actual_cmd.icon, show_synth_create_cmd, SparkCommands.KeyGestures.ShowSyntheticCreate);
var show_working_orders_cmd = new DelegateCommand(() => _view.show_working_orders(_vm.selected_securities), () => _vm.selected_securities.Count > 0);
var update_securities_cmd = SparkCommands.change_securities_callback(_window_type_display_name); var current_sec_md_src = Observable.Create<SecurityMD?>(o => {
// commands notify(null, null);
_vm.current_row_changed += notify;
return Disposable.Create(() => _vm.current_row_changed -= notify);
void notify(MarketViewVM.Row oldval, MarketViewVM.Row newval) {
if (newval != null)
o.OnNext(newval.security_md);
else o.OnNext(null);
}
});
_commands = new List<SparkCommand> { _commands = new List<SparkCommand> {
SparkCommands.ShowLadders(SparkCommands.KeyGestures.ShowLadder).complete(_vm.selected_security_mds_observable(), smds => smds.Count > 0), SparkCommands.ShowLadders(SparkCommands.KeyGestures.ShowLadder).complete(_vm.selected_rows.Observe().Select(_ => _vm.selected_rows.WrapSelectorRO(r => r.security_md)), smds => smds.Count > 0),
SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket).complete(_vm.current_security_md, md => md.HasValue, ConvertUtils.ValueOrDefault), SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket).complete(current_sec_md_src, md => md.HasValue, ConvertUtils.ValueOrDefault),
show_fills_cmd_wrapper, show_fills_cmd_wrapper,
show_tas_cmd_wrapper, show_tas_cmd_wrapper,
show_synth_create_cmd_wrapper, show_synth_create_cmd_wrapper,
// Note: the commands commented out below open the mini popup versions of their respective windows
// TODO: determine if/how to integrate the mini popups into the toolbar.
//new SparkCommandCommand("Working Orders", Icons.Orders, show_working_orders_cmd),
//new SparkCommandCommand("Fills", show_fills_actual_cmd.icon, show_mini_fills_cmd),
//new SparkCommandCommand(show_ticket_actual_cmd.title, show_ticket_actual_cmd.icon, show_ticket_cmd),
SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)), 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 // 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(() => { SparkCommands.window_settings_command(new DialogCommand(() => {
@@ -150,7 +192,7 @@ namespace mbts.spark {
_settings_manager, _settings_manager,
us => us.market_view_grid, us => us.market_view_grid,
UserSettings.FileExtensions.GRID, UserSettings.FileExtensions.GRID,
s => _vm.grid_settings_manager.create_vm( s => _grid_settings_manager.create_vm(
// we need to get the most up to date GridSettings when launching b/c users may // we need to get the most up to date GridSettings when launching b/c users may
// have changed some settings on the grid directly, like column widths. // have changed some settings on the grid directly, like column widths.
s.with(_vm.columns.Select(c => c.create())) s.with(_vm.columns.Select(c => c.create()))
@@ -163,26 +205,40 @@ namespace mbts.spark {
})) }))
}; };
// //
_vm.selection_changed += on_selection_changed; _vm.selected_rows.CollectionChanged += on_selection_changed;
_subscriptions = new CompositeDisposable(_bus.subscribe(update_securities_cmd.tag).OnDispatcher().Subscribe(c => _subscriptions = new CompositeDisposable(
_state_changed?.Invoke(_state = new MarketViewWindowFactory.StartupData(c, _vm.get_filter_states(), _vm.grid_settings_manager.create())))) { _bus.subscribe(update_securities_cmd.tag).OnDispatcher().Subscribe(c => {
_state = new MarketViewWindowFactory.StartupData(c, _state.filters, _state.grid, _state.sorting_criterion.ToList());
_security_criteria_changed?.Invoke(c);
}),
_settings_manager.subscribe_current().OnDispatcher().Subscribe(new CompositeObserver<GridSettings>(_grid_settings_manager) {
s => _vm.selection_highlight = s.selection_highlight
})) {
() => { () => {
_vm.selection_changed -= on_selection_changed; _vm.selected_rows.CollectionChanged -= on_selection_changed;
_view._grid.Sorting -= on_grid_sorting; _view._grid.Sorting -= on_grid_sorting;
} }
}; };
void on_selection_changed((IEnumerable<MarketViewVM.Row> removed, IEnumerable<MarketViewVM.Row> added) change) { void on_selection_changed(object sender, NotifyCollectionChangedEventArgs e) {
// invalidate selected security criteria // invalidate selected security criteria
_selected_security_criteria_backing = null; _selected_security_criteria_backing = null;
_sorted_selected_security_criteria_backing = null; _sorted_selected_security_criteria_backing = null;
show_tas_cmd.RaiseCanExecuteChanged(); show_tas_cmd.RaiseCanExecuteChanged();
show_fills_cmd.RaiseCanExecuteChanged(); show_fills_cmd.RaiseCanExecuteChanged();
show_synth_create_cmd.RaiseCanExecuteChanged(); show_synth_create_cmd.RaiseCanExecuteChanged();
show_working_orders_cmd.RaiseCanExecuteChanged();
show_mini_fills_cmd.RaiseCanExecuteChanged();
show_ticket_cmd.RaiseCanExecuteChanged();
} }
void on_grid_sorting(object sender, ui.controls.DIYGridSortingEventArgs e) => void on_grid_sorting(object sender, ui.controls.DIYGridSortingEventArgs e) {
_sorted_selected_security_criteria_backing = null; _sorted_selected_security_criteria_backing = null;
sort_man.on_column_click(e.Column, KeyboardExtensions.IsShiftDown());
_vm.comparer = sort_man.build_comparer<MarketViewView.Columns, MarketViewVM.Row>(MarketViewVM.get_column_comparer);
_current_sorting_criterion = sort_man.create().ToList();
e.Handled = true;
}
} }
public override void Dispose() { public override void Dispose() {
@@ -1,6 +1,7 @@
using bts.api; using bts.api;
using bts.proto; using bts.proto;
using bts.settings; using bts.settings;
using bts.utils;
using mbts.persist; using mbts.persist;
using mbts.spark; using mbts.spark;
using mbts.spark.filters; using mbts.spark.filters;
@@ -88,7 +89,19 @@ namespace bts.shell {
} }
public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion, enable_background_color: true); public static GridSettings DefaultGridSettings =>
GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion, enable_background_color: true);
public static fills.FillsSettings DefaultAuxiliaryFills {
get {
var col_keys = new HashSet<mbts.ui.spark.FillsView.Columns>(
fills.FillsSettings.mini_column_keys);
col_keys.Add(mbts.ui.spark.FillsView.Columns.Account);
var rv = fills.FillsSettings.Default();
rv.grid = fills.FillsSettings.create_grid(col_keys);
return rv;
}
}
public IReadOnlyList<SortingCriteria> sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList()); public IReadOnlyList<SortingCriteria> sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList());
@@ -196,7 +209,7 @@ namespace bts.shell {
[ProtoMember(11)] [ProtoMember(11)]
public DoubleMinMaxState session_high; public DoubleMinMaxState session_high;
[ProtoMember(12)] [ProtoMember(12)]
public IntMinMaxState position; public IntMinMaxState day_position;
[ProtoMember(27)] [ProtoMember(27)]
public DoubleMinMaxState raw_day_position; public DoubleMinMaxState raw_day_position;
[ProtoMember(13)] [ProtoMember(13)]
@@ -229,6 +242,47 @@ namespace bts.shell {
public string last_price_from_spread; public string last_price_from_spread;
[ProtoMember(28)] [ProtoMember(28)]
public string mic_code; public string mic_code;
public Func<MarketViewVM.Row, bool> build_predicate() {
var pb = new ColumnPredicateBuilder<MarketViewVM.Row>();
// security
pb.add_regex(security, r => r.security.ToString());
pb.add_regex(security_key, r => r.security_key.ToString());
// bid
pb.add_numeric(bid_price, r => r.bid_price);
pb.add_numeric(bid_merged_size, r => r.bid_merged_size);
pb.add_numeric(bid_direct_size, r => r.bid_direct_size);
pb.add_numeric(bid_implied_size, r => r.bid_implied_size);
pb.add_numeric(working_bid_volume, r => r.working_bid_volume);
// ask
pb.add_numeric(ask_price, r => r.ask_price);
pb.add_numeric(ask_implied_size, r => r.ask_implied_size);
pb.add_numeric(ask_direct_size, r => r.ask_direct_size);
pb.add_numeric(ask_merged_size, r => r.ask_merged_size);
pb.add_numeric(working_ask_volume, r => r.working_ask_volume);
// last
pb.add_numeric(last_price, r => r.last_price);
pb.add_regex(last_price_from_spread, r => r.last_price_from_spread.ToString());
pb.add_numeric(last_size, r => r.last_size);
// position
// TODO: convert day_position to DoubleMinMaxState
pb.add_numeric(day_position, r => unchecked((int)r.day_position));
pb.add_numeric(raw_day_position, r => r.raw_day_position);
// market
pb.add_numeric(day_change, r => r.day_change);
pb.add_numeric(settlement, r => r.settlement);
pb.add_numeric(session_low, r => r.session_low);
pb.add_numeric(session_high, r => r.session_high);
pb.add_numeric(volume, r => r.volume);
// ice
pb.add_regex(market_description, r => r.market_description);
pb.add_regex(cleared_alias, r => r.cleared_alias);
pb.add_regex(product_description, r => r.product_description);
pb.add_regex(hub_alias, r => r.hub_alias);
pb.add_regex(strip_name, r => r.strip_name);
pb.add_regex(mic_code, r => r.mic_code);
return pb.to_predicate();
}
} }
// migration rules // migration rules
@@ -271,5 +325,11 @@ namespace bts.shell {
return false; return false;
} }
} }
[Export(typeof(IMarketViewGridSettingsMigrationRule))]
class EnsureSelectionHighlightTranslucency : IMarketViewGridSettingsMigrationRule {
public bool apply(GridSettings settings, out GridSettings new_settings) =>
GridSettingsMigrationRules.SelectionHighlightIsTranslucent.apply(settings, out new_settings);
}
} }
} }
@@ -13,5 +13,5 @@ namespace mbts.ui.spark {
InitializeComponent(); InitializeComponent();
} }
class TimeAndSalesRowView : DIYGrid.HighPerformanceRow<TimeAndSalesVM.Row, TimeAndSalesView.Columns> { } class TimeAndSalesRowView : DIYGrid.HighPerformanceRow<TimeAndSalesVM.Row> { }
} }
@@ -20,5 +20,5 @@ namespace mbts.ui.spark {
InitializeComponent(); InitializeComponent();
} }
class SyntheticManagementRowView : DIYGrid.HighPerformanceRow<SyntheticManagementDialogVM.Row, SyntheticManagementView.Columns> { } class SyntheticManagementRowView : DIYGrid.HighPerformanceRow<SyntheticManagementDialogVM.Row> { }
} }
@@ -47,13 +47,13 @@ namespace mbts.spark {
add_col(Columns.Name, DefaultColumnHeaders.Name, r => r.name, nameof(Row.name), name_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.Security); add_col(Columns.Name, DefaultColumnHeaders.Name, r => r.name, nameof(Row.name), name_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.Security);
add_col(Columns.Description, DefaultColumnHeaders.Description, r => r.description, nameof(Row.description), description_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.Description); add_col(Columns.Description, DefaultColumnHeaders.Description, r => r.description, nameof(Row.description), description_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.Description);
add_col(Columns.n_legs, DefaultColumnHeaders.N_Legs, r => r.n_legs.ToString(), nameof(Row.n_legs), n_legs_filter, DataGridFilterKnownTemplates.IntMinMax, DefaultColumnWidths.N_Legs); add_col(Columns.n_legs, DefaultColumnHeaders.N_Legs, r => r.n_legs.ToString(), nameof(Row.n_legs), n_legs_filter, DataGridFilterKnownTemplates.IntMinMax, DefaultColumnWidths.N_Legs);
columns.Add(new HyperlinkElementColumn<Row, Columns>( columns.Add(new HyperlinkElementColumn<Columns>(
Columns.n_working_orders, Columns.n_working_orders,
new Binding(nameof(Row.n_working_orders)),
new Binding(nameof(Row.show_order_book)),
n_working_orders_filter, n_working_orders_filter,
DataGridFilterKnownTemplates.UIntMinMax) { DataGridFilterKnownTemplates.UIntMinMax) {
id = col_id(Columns.n_working_orders), id = col_id(Columns.n_working_orders),
CommandBinding = new Binding(nameof(Row.show_order_book)),
TextBinding = new Binding(nameof(Row.n_working_orders)),
Header = DefaultColumnHeaders.N_Working_Orders, Header = DefaultColumnHeaders.N_Working_Orders,
Width = DefaultColumnWidths.N_Working_Orders Width = DefaultColumnWidths.N_Working_Orders
}); });
@@ -214,10 +214,13 @@ namespace mbts.spark {
((IKeyedColumn<Columns>)column).key; ((IKeyedColumn<Columns>)column).key;
static IObservable<TableUpdate<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, FillsSettings state) { static IObservable<TableUpdate<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, FillsSettings state) {
if (!state.orders.is_null_or_empty()) { var orders_hash = state.orders.is_null_or_empty() ? null : new HashSet<uint>(state.orders);
var orders_hash = new HashSet<uint>(state.orders); var root_securities_hash = state.root_securities.is_null_or_empty() ? null : new HashSet<uint>(state.root_securities);
return model.on_fill_tuples_with_root.Filter(f => orders_hash.Contains(f.fill.OrderKey)); return orders_hash == null && root_securities_hash == null ?
} else return model.on_fill_tuples_with_root; model.on_fill_tuples_with_root :
model.on_fill_tuples_with_root.Filter(f =>
(orders_hash == null || orders_hash.Contains(f.fill.OrderKey)) &&
(root_securities_hash == null || root_securities_hash.Contains(f.root_order_security?.security?.Id ?? 0)));
} }
static IObservable<TableUpdate<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, IObservable<FillsSettings> state) => static IObservable<TableUpdate<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, IObservable<FillsSettings> state) =>
@@ -31,5 +31,5 @@ namespace mbts.ui.spark {
InitializeComponent(); InitializeComponent();
} }
class FillsRowView : DIYGrid.HighPerformanceRow<FillsVM.Row, FillsView.Columns> { } class FillsRowView : DIYGrid.HighPerformanceRow<FillsVM.Row> { }
} }
@@ -72,5 +72,11 @@ namespace bts.shell {
public bool apply(GridSettings settings, out GridSettings new_settings) => public bool apply(GridSettings settings, out GridSettings new_settings) =>
settings.add_missing_columns(FillsSettings.DefaultGridSettings.columns, out new_settings); settings.add_missing_columns(FillsSettings.DefaultGridSettings.columns, out new_settings);
} }
[Export(typeof(IFillsGridSettingsMigrationRule))]
class EnsureSelectionHighlightTranslucency : IFillsGridSettingsMigrationRule {
public bool apply(GridSettings settings, out GridSettings new_settings) =>
GridSettingsMigrationRules.SelectionHighlightIsTranslucent.apply(settings, out new_settings);
}
} }
} }
@@ -1,4 +1,5 @@
using mbts.ui; using bts.collections;
using mbts.ui;
using mbts.ui.settings; using mbts.ui.settings;
using ProtoBuf; using ProtoBuf;
using System; using System;
@@ -34,10 +35,28 @@ namespace bts.shell.fills {
public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion);
public static GridSettings MiniGridSettings => GridSettings.Default.with(DefaultColumns.Mini.all, DefaultColumns.Mini.sorting_criterion); public static GridSettings MiniGridSettings => GridSettings.Default.with(DefaultColumns.Mini.all, DefaultColumns.Mini.sorting_criterion);
public static IEnumerable<Columns> mini_column_keys => DefaultColumns.Mini.mini_cols_data.Keys;
public IReadOnlyList<SortingCriteria> sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList()); public IReadOnlyList<SortingCriteria> sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList());
public uint[] root_securities { get; set; }
public static FillsSettings Default() => public static FillsSettings Default() =>
new FillsSettings(null, null, new FillsFilterStates(), null); new FillsSettings(null, null, new FillsFilterStates(), null);
public static GridSettings create_grid(IEnumerable<Columns> keys) {
var key_set = keys as ISet<Columns> ?? new HashSet<Columns>(keys.empty_if_null());
var grid = DefaultGridSettings;
var cols = new LazyMutatorList<GridColumnSettings>(grid.columns);
for (int i = 0; i < cols.Count; i++) {
var c = cols[i];
if (c.is_visible != key_set.Contains(c.strong_id<Columns>()))
cols[i] = c.with(is_visible: !c.is_visible);
}
if (cols.IsMutated)
grid = grid.with(cols);
return grid;
}
static class DefaultColumns { static class DefaultColumns {
public static GridColumnSettings security => new GridColumnSettings(col_id(Columns.Security), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security); public static GridColumnSettings security => new GridColumnSettings(col_id(Columns.Security), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security);
public static GridColumnSettings symbol => new GridColumnSettings(col_id(Columns.Symbol), DefaultColumnHeaders.Symbol, width: DefaultColumnWidths.Symbol); public static GridColumnSettings symbol => new GridColumnSettings(col_id(Columns.Symbol), DefaultColumnHeaders.Symbol, width: DefaultColumnWidths.Symbol);
@@ -83,21 +102,21 @@ namespace bts.shell.fills {
} }
public static class Mini { public static class Mini {
static readonly IReadOnlyDictionary<Columns, (bool is_visible, double? width_override)> _mini_cols_data = public static readonly IReadOnlyDictionary<Columns, (bool is_visible, double? width_override)> mini_cols_data =
new Dictionary<Columns, (bool is_visible, double? width_override)> { new Dictionary<Columns, (bool is_visible, double? width_override)> {
{ Columns.Security, (true, null) }, { Columns.Security, (true, null) },
{ Columns.FillTime, (true, ShortColumnWidths.Time) }, { Columns.FillTime, (true, ShortColumnWidths.Time) },
{ Columns.OrderType, (true, ShortColumnWidths.OrderType) }, { Columns.OrderType, (true, ShortColumnWidths.OrderType) },
{ Columns.Side, (true, ShortColumnWidths.Side) }, { Columns.Side, (true, ShortColumnWidths.Side) },
{ Columns.Size, (true, ShortColumnWidths.Size) }, { Columns.Size, (true, ShortColumnWidths.Size) },
{ Columns.Price, (true, ShortColumnWidths.Price) }, { Columns.Price, (true, ShortColumnWidths.Price) }
}; };
public static IEnumerable<GridColumnSettings> all => DefaultColumns.all.Select(_convert); public static IEnumerable<GridColumnSettings> all => DefaultColumns.all.Select(_convert);
public static IEnumerable<SortingCriteria> sorting_criterion => default_sorting_criterion.Where(c => _try_get_data(c.col_name, out (bool is_visible, double? _) d) && d.is_visible); public static IEnumerable<SortingCriteria> sorting_criterion => default_sorting_criterion.Where(c => _try_get_data(c.col_name, out (bool is_visible, double? _) d) && d.is_visible);
static bool _try_get_data(string id_str, out (bool is_visible, double? width_override) data) { static bool _try_get_data(string id_str, out (bool is_visible, double? width_override) data) {
if (Enum.TryParse(id_str, out Columns k) && _mini_cols_data.TryGetValue(k, out data)) if (Enum.TryParse(id_str, out Columns k) && mini_cols_data.TryGetValue(k, out data))
return true; return true;
data = default; data = default;
return false; return false;
@@ -110,4 +129,4 @@ namespace bts.shell.fills {
} }
} }
} }
} }
@@ -12,7 +12,6 @@ using mbts.ui.spark.algo;
using mbts.ui.utility.text; using mbts.ui.utility.text;
using mbts.utils; using mbts.utils;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Collections.Specialized; using System.Collections.Specialized;
@@ -256,9 +255,8 @@ namespace mbts.spark {
DependencyProperty.Register("Orders", typeof(ObservableCollection<LadderOrderVM>), typeof(LadderGridHost), new PropertyMetadata(null, orders_changed)); DependencyProperty.Register("Orders", typeof(ObservableCollection<LadderOrderVM>), typeof(LadderGridHost), new PropertyMetadata(null, orders_changed));
static void orders_changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { static void orders_changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
LadderGridHost lgh = d as LadderGridHost; if (d is LadderGridHost lgh)
WPFHelper.manage_collection_change(e, lgh.orders_collection_changed, src => lgh._ordershost.clear_orders(), WPFHelper.manage_collection_change(e, lgh.orders_collection_changed);
src => lgh.orders_collection_changed(lgh, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, (IList)src)));
} }
void orders_collection_changed(object sender, NotifyCollectionChangedEventArgs e) { void orders_collection_changed(object sender, NotifyCollectionChangedEventArgs e) {
@@ -22,7 +22,7 @@ namespace mbts.spark {
DataContext = vm; DataContext = vm;
} }
class MiniOrderBookRowView : DIYGrid.HighPerformanceRow<OrderBookRowVM, OrderBookGridView.ColumnKeys> { class MiniOrderBookRowView : DIYGrid.HighPerformanceRow<OrderBookRowVM> {
public MiniOrderBookRowView() : base() { public MiniOrderBookRowView() : base() {
FocusManager.SetIsFocusScope(this, true); FocusManager.SetIsFocusScope(this, true);
KeyboardNavigation.SetTabNavigation(this, KeyboardNavigationMode.Cycle); KeyboardNavigation.SetTabNavigation(this, KeyboardNavigationMode.Cycle);
@@ -650,12 +650,13 @@ namespace mbts.spark {
ListSortDirection? _cached_sort_direction; ListSortDirection? _cached_sort_direction;
public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, string> filter) public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter<OrderSecurityRootPair, string> filter)
: base(Columns.LastMessage, new Binding(nameof(OrderBookRowVM.last_msg)), filter, DataGridFilterKnownTemplates.Regex) { : base(Columns.LastMessage, filter, DataGridFilterKnownTemplates.Regex) {
id = key.ToString(); id = key.ToString();
this.filter = filter; this.filter = filter;
Header = "Last Message"; Header = "Last Message";
Width = DefaultColumnWidths.LastMessage; Width = DefaultColumnWidths.LastMessage;
tooltip_binding = new Binding(nameof(OrderBookRowVM.last_msg)); TextBinding = new Binding(nameof(OrderBookRowVM.last_msg));
ToolTipBinding = new Binding(nameof(OrderBookRowVM.last_msg));
} }
public new IDataGridColumnPersistentFilter<OrderSecurityRootPair, string> filter { get; } public new IDataGridColumnPersistentFilter<OrderSecurityRootPair, string> filter { get; }
@@ -7,6 +7,7 @@ using mbts.ui;
using System; using System;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Media;
namespace bts.shell { namespace bts.shell {
internal class OrderBookWindowFactory : ShellWindowFactory<OrderBookStartupData> { internal class OrderBookWindowFactory : ShellWindowFactory<OrderBookStartupData> {
@@ -26,6 +27,14 @@ namespace bts.shell {
} }
public override Task<IShellWindow> load(OrderBookStartupData state) { public override Task<IShellWindow> load(OrderBookStartupData state) {
// A fairly major grid settings revamp is in the works,
// which will correctly negotiate background color settings as defined at the grid and column level.
// The hack is neccessary bc a previously benign bug (which has been fixed in this 'mview popups' patch) in the GridSettingsVM
// always changed the grid background color to black.
// Fortunately, the bug only affects the OrderBook as other windows use SimpleGridSettingsVM, which does not have such a bug.
if (state != null && !state.orderbook_grid.general.enable_background_color && state.orderbook_grid.general.background_color.argb_color().A > 0) {
state.orderbook_grid.general = state.orderbook_grid.general.with(background: Colors.Transparent.rgb_color());
}
var settings_manager = new WindowSettingsManager<OrderBookGridSettings>(_settings_hub, state.grid_settings_wrapper(), var settings_manager = new WindowSettingsManager<OrderBookGridSettings>(_settings_hub, state.grid_settings_wrapper(),
us => us.order_book_grid ?? OrderBookStartupData.DefaultGrid, us => us.order_book_grid ?? OrderBookStartupData.DefaultGrid,
(us, s) => us.with(order_book_grid: s)); (us, s) => us.with(order_book_grid: s));
@@ -9,7 +9,6 @@
xmlns:usp="clr-namespace:mbts.ui.spark" xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:uspcv="clr-namespace:mbts.ui.spark.converters" xmlns:uspcv="clr-namespace:mbts.ui.spark.converters"
xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:sys="clr-namespace:System;assembly=mscorlib"
InactiveSelectionOpacity="0.3"
> >
<c:DIYGrid.Resources> <c:DIYGrid.Resources>
<ResourceDictionary> <ResourceDictionary>
@@ -99,7 +99,7 @@ namespace mbts.spark {
} }
} }
class OrderBookRowView : DIYGrid.HighPerformanceRow<OrderBookRowVM, OrderBookGridView.ColumnKeys> { class OrderBookRowView : DIYGrid.HighPerformanceRow<OrderBookRowVM> {
public OrderBookRowView() : base() { } public OrderBookRowView() : base() { }
} }
} }
@@ -49,8 +49,9 @@ namespace bts.shell.pnl {
PNLHeaderRowDisplay _header_row_display = PNLHeaderRowDisplay.Total; PNLHeaderRowDisplay _header_row_display = PNLHeaderRowDisplay.Total;
PNLRowCollectionView _rows_view; PNLRowCollectionView _rows_view;
IReadOnlyList<(ColumnKeys key, ListSortDirection direction)> _sorting_hierarchy; IReadOnlyList<(ColumnKeys key, ListSortDirection direction)> _sorting_hierarchy;
Brush _selection_highlight; Color
Color _grid_background_color = Colors.Transparent; _grid_background_color = Colors.Transparent,
_selection_highlight;
bool _is_paused; bool _is_paused;
// default appearances // default appearances
ImmutableDictionary<ColumnKeys, PNLCellAppearance> ImmutableDictionary<ColumnKeys, PNLCellAppearance>
@@ -175,7 +176,7 @@ namespace bts.shell.pnl {
} }
} }
public Brush selection_highlight { get => _selection_highlight; set => Set(ref _selection_highlight, value); } public Color selection_highlight { get => _selection_highlight; set => Set(ref _selection_highlight, value); }
public Color grid_background_color { get => _grid_background_color; set => Set(ref _grid_background_color, value); } public Color grid_background_color { get => _grid_background_color; set => Set(ref _grid_background_color, value); }
public IValueConverter group_background_converter => _group_background_converter; public IValueConverter group_background_converter => _group_background_converter;
@@ -291,7 +292,7 @@ namespace bts.shell.pnl {
}; };
public void load_from(PNLSettings settings) { public void load_from(PNLSettings settings) {
selection_highlight = settings.grid.selection_highlight.to_brush(); selection_highlight = settings.grid.selection_highlight;
grid_background_color = settings.grid.background; grid_background_color = settings.grid.background;
calculation_type = settings.calculation_type; calculation_type = settings.calculation_type;
if (settings.filters != null) { if (settings.filters != null) {
@@ -381,7 +382,7 @@ namespace bts.shell.pnl {
_append_key_filters(state.filters, key); _append_key_filters(state.filters, key);
_append_row_filters(state.filters, row); _append_row_filters(state.filters, row);
// hide implicit cols // hide implicit cols
state.grid = _hide_cols(state.grid, anchors); state.grid = GridSettingsHelper.hide_cols(state.grid, anchors);
return new FillsVM( return new FillsVM(
_bus, _orders_model, Observable.Return(state), new WindowSettingsManager<GridSettings>.DisconnectedImpl(state.grid)); _bus, _orders_model, Observable.Return(state), new WindowSettingsManager<GridSettings>.DisconnectedImpl(state.grid));
} }
@@ -391,7 +392,7 @@ namespace bts.shell.pnl {
_append_key_filters(state.filters, key); _append_key_filters(state.filters, key);
_append_group_filters(state.filters, group, anchors); _append_group_filters(state.filters, group, anchors);
// hide implicit cols // hide implicit cols
state.grid = _hide_cols(state.grid, anchors.WrapSubRange(0, group.level)); state.grid = GridSettingsHelper.hide_cols(state.grid, anchors.WrapSubRange(0, group.level));
return new FillsVM( return new FillsVM(
_bus, _orders_model, Observable.Return(state), _visible_fills_source(), new WindowSettingsManager<GridSettings>.DisconnectedImpl(state.grid)); _bus, _orders_model, Observable.Return(state), _visible_fills_source(), new WindowSettingsManager<GridSettings>.DisconnectedImpl(state.grid));
} }
@@ -401,7 +402,7 @@ namespace bts.shell.pnl {
state.grid = orderbook.OrderBookStartupData.DefaultFillsGrid.general; state.grid = orderbook.OrderBookStartupData.DefaultFillsGrid.general;
state.filters = new fills.FillsFilterStates(); state.filters = new fills.FillsFilterStates();
// hide implicit cols // hide implicit cols
state.grid = _hide_cols(orderbook.OrderBookStartupData.DefaultFillsGrid.general, anchors); state.grid = GridSettingsHelper.hide_cols(orderbook.OrderBookStartupData.DefaultFillsGrid.general, anchors);
_append_key_filters(state.filters, key); _append_key_filters(state.filters, key);
var src = _orders_model.on_fill_tuples; var src = _orders_model.on_fill_tuples;
switch (header) { switch (header) {
@@ -532,16 +533,6 @@ namespace bts.shell.pnl {
new PNLColumnComparer<T>(selector); new PNLColumnComparer<T>(selector);
} }
static GridSettings _hide_cols(GridSettings grid, IEnumerable<ColumnKeys> columns) =>
grid.with(_hide_cols(grid.columns, columns));
static IEnumerable<GridColumnSettings> _hide_cols(IEnumerable<GridColumnSettings> cols, IEnumerable<ColumnKeys> columns) {
// hide columns who's data is implied by the grouping
var col_hash = new HashSet<string>(columns.Select(k => k.ToString()));
foreach (var c in cols)
yield return col_hash.Contains(c.id) ? c.with(is_visible: false) : c;
}
#region Fills Popup Utils #region Fills Popup Utils
static void _append_key_filters(fills.FillsFilterStates f, ColumnKeys key) { static void _append_key_filters(fills.FillsFilterStates f, ColumnKeys key) {
switch (key) { switch (key) {
@@ -680,7 +671,7 @@ namespace bts.shell.pnl {
OrderBookVM _mk_orderbook_vm_common(orderbook.FilterStates filters, IEnumerable<ColumnKeys> hide_counterparts, IObservable<TableUpdate<OrderSecurityRootPair, uint>> orders_source = null) { OrderBookVM _mk_orderbook_vm_common(orderbook.FilterStates filters, IEnumerable<ColumnKeys> hide_counterparts, IObservable<TableUpdate<OrderSecurityRootPair, uint>> orders_source = null) {
var state = new orderbook.OrderBookStartupData(filters, orderbook.OrderBookStartupData.default_mini_grid, use_defaults: false); var state = new orderbook.OrderBookStartupData(filters, orderbook.OrderBookStartupData.default_mini_grid, use_defaults: false);
state.orderbook_grid.general = _hide_cols(state.orderbook_grid.general, hide_counterparts); state.orderbook_grid.general = GridSettingsHelper.hide_cols(state.orderbook_grid.general, hide_counterparts);
var settings_man = new WindowSettingsManager<orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid); var settings_man = new WindowSettingsManager<orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
var obvm = orders_source == null ? var obvm = orders_source == null ?
new OrderBookVM(_bus, null, _orders_model, settings_man, true) : new OrderBookVM(_bus, null, _orders_model, settings_man, true) :
@@ -4,6 +4,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pnl="clr-namespace:bts.shell.pnl" xmlns:pnl="clr-namespace:bts.shell.pnl"
xmlns:bv="clr-namespace:bts.view"
xmlns:ft="clr-namespace:mbts.spark.filters" xmlns:ft="clr-namespace:mbts.spark.filters"
xmlns:u="clr-namespace:mbts.ui" xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls" xmlns:c="clr-namespace:mbts.ui.controls"
@@ -11,7 +12,9 @@
xmlns:usp="clr-namespace:mbts.ui.spark" xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:sys="clr-namespace:System;assembly=mscorlib"
FocusManager.IsFocusScope="True" FocusManager.IsFocusScope="True"
u:WindowStyle.UnsafeWindow="{Binding Path='(u:WindowStyle.UnsafeWindow)', RelativeSource={RelativeSource AncestorType=bv:SparkWindowView}}"
Background="{StaticResource CommonBackground}" Background="{StaticResource CommonBackground}"
Tag="{Binding ElementName=_grid}"
> >
<UserControl.CommandBindings> <UserControl.CommandBindings>
<CommandBinding Command="{x:Static pnl:PNLView.CellClickCommand}" Executed="_cell_click_executed"/> <CommandBinding Command="{x:Static pnl:PNLView.CellClickCommand}" Executed="_cell_click_executed"/>
@@ -29,6 +32,10 @@
<Color x:Key="GroupRowForegroundColor">#FF000000</Color> <Color x:Key="GroupRowForegroundColor">#FF000000</Color>
<!--Converters--> <!--Converters-->
<cv:GridLengthConverter x:Key="GridLengthPixelConverter" UnitType="Pixel"/> <cv:GridLengthConverter x:Key="GridLengthPixelConverter" UnitType="Pixel"/>
<cv:ValueConverterPipe x:Key="GroupRowHeightConverter">
<cv:RangeBlockConverter Minimum="{x:Static pnl:PNLView.MinGroupRowHeight}"/>
<cv:GridLengthConverter UnitType="Pixel"/>
</cv:ValueConverterPipe>
<cv:MultiValueConverterPipe x:Key="GroupRowBackgroundConverter"> <cv:MultiValueConverterPipe x:Key="GroupRowBackgroundConverter">
<cv:PartialConverter/> <cv:PartialConverter/>
<cv:ColorToBrushConverter/> <cv:ColorToBrushConverter/>
@@ -258,7 +265,7 @@
</Setter> </Setter>
</Style> </Style>
<Style x:Key="RowTextCell" TargetType="c:TextCell"> <Style x:Key="TextCellBase" TargetType="c:TextCell">
<Setter Property="Background"> <Setter Property="Background">
<Setter.Value> <Setter.Value>
<SolidColorBrush Color="{Binding background}"/> <SolidColorBrush Color="{Binding background}"/>
@@ -269,10 +276,14 @@
<SolidColorBrush Color="{Binding foreground}"/> <SolidColorBrush Color="{Binding foreground}"/>
</Setter.Value> </Setter.Value>
</Setter> </Setter>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="FontWeight" Value="{Binding font_weight}"/> <Setter Property="FontWeight" Value="{Binding font_weight}"/>
<Setter Property="FontSize" Value="{Binding font_size}"/> <Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Text" Value="{Binding text}"/> <Setter Property="Text" Value="{Binding text}"/>
<Setter Property="SnapsToDevicePixels" Value="True"/>
</Style>
<Style x:Key="RowTextCell" TargetType="c:TextCell" BasedOn="{StaticResource TextCellBase}">
<Setter Property="FontSize" Value="{Binding font_size}"/>
<Setter Property="c:DIYGrid.ObservedCachedColumnParams"> <Setter Property="c:DIYGrid.ObservedCachedColumnParams">
<Setter.Value> <Setter.Value>
<x:Array Type="{x:Type c:CachedColumnParam}"> <x:Array Type="{x:Type c:CachedColumnParam}">
@@ -284,20 +295,7 @@
</Setter> </Setter>
</Style> </Style>
<Style x:Key="GroupRowTextCell" TargetType="c:TextCell"> <Style x:Key="GroupRowTextCell" TargetType="c:TextCell" BasedOn="{StaticResource TextCellBase}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding background}"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{Binding foreground}"/>
</Setter.Value>
</Setter>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="FontWeight" Value="{Binding font_weight}"/>
<Setter Property="Text" Value="{Binding text}"/>
<Setter Property="c:DIYGrid.ObservedCachedColumnParams"> <Setter Property="c:DIYGrid.ObservedCachedColumnParams">
<Setter.Value> <Setter.Value>
<x:Array Type="{x:Type c:CachedColumnParam}"> <x:Array Type="{x:Type c:CachedColumnParam}">
@@ -309,21 +307,8 @@
</Setter> </Setter>
</Style> </Style>
<Style x:Key="HeaderRowTextCell" TargetType="c:TextCell"> <Style x:Key="HeaderRowTextCell" TargetType="c:TextCell" BasedOn="{StaticResource TextCellBase}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding background}"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{Binding foreground}"/>
</Setter.Value>
</Setter>
<Setter Property="Margin" Value="0,0,0,1"/> <Setter Property="Margin" Value="0,0,0,1"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="FontWeight" Value="{Binding font_weight}"/>
<Setter Property="Text" Value="{Binding text}"/>
<Setter Property="c:DIYGrid.ObservedCachedColumnParams"> <Setter Property="c:DIYGrid.ObservedCachedColumnParams">
<Setter.Value> <Setter.Value>
<x:Array Type="{x:Type c:CachedColumnParam}"> <x:Array Type="{x:Type c:CachedColumnParam}">
@@ -335,7 +320,23 @@
</Setter> </Setter>
</Style> </Style>
<Style x:Key="HyperlinkCell" TargetType="c:HyperlinkCell"> <Style x:Key="HyperlinkCellBase" TargetType="c:HyperlinkCell">
<Setter Property="c:DIYGrid.Grid" Value="{Binding RelativeSource={RelativeSource AncestorType=c:DIYGrid}}"/>
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding background}"/>
</Setter.Value>
</Setter>
<Setter Property="BorderBrush">
<Setter.Value>
<SolidColorBrush Color="{Binding border}"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{Binding foreground}"/>
</Setter.Value>
</Setter>
<Setter Property="HorizontalAlignment" Value="Stretch"/> <Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="VerticalAlignment" Value="Stretch"/> <Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/> <Setter Property="VerticalContentAlignment" Value="Stretch"/>
@@ -349,41 +350,46 @@
</MultiBinding> </MultiBinding>
</Setter.Value> </Setter.Value>
</Setter> </Setter>
<Setter Property="c:DIYGrid.ObservedCachedColumnParams">
<Setter.Value>
<x:Array Type="{x:Type c:CachedColumnParam}">
<c:CachedColumnParam SourcePropertyName="font_family" TargetProperty="c:HyperlinkCell.FontFamily"/>
<c:CachedColumnParam SourcePropertyName="font_size" TargetProperty="c:HyperlinkCell.FontSize"/>
<c:CachedColumnParam SourcePropertyName="font_brush" TargetProperty="c:HyperlinkCell.Foreground"/>
<c:CachedColumnParam SourcePropertyName="horizontal_alignment" TargetProperty="c:HyperlinkCell.HorizontalContentAlignment"/>
</x:Array>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="RowHyperlinkCell" TargetType="c:HyperlinkCell">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding background}"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{Binding foreground}"/>
</Setter.Value>
</Setter>
<Setter Property="BorderBrush">
<Setter.Value>
<SolidColorBrush Color="{Binding border}"/>
</Setter.Value>
</Setter>
<Setter Property="Padding" Value="{x:Static c:DIYGrid.AnimatableCellPadding}"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="FontWeight" Value="{Binding font_weight}"/> <Setter Property="FontWeight" Value="{Binding font_weight}"/>
<Setter Property="FontSize" Value="{Binding font_size}"/> <Setter Property="FontSize" Value="{Binding font_size}"/>
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="Text" Value="{Binding text}"/> <Setter Property="Text" Value="{Binding text}"/>
<Setter Property="Command" Value="{x:Static pnl:PNLView.CellClickCommand}"/> <Style.Triggers>
<Setter Property="CommandTarget" Value="{Binding RelativeSource={RelativeSource AncestorType=pnl:PNLView}}"/> <Trigger Property="IsMouseOverClickArea" Value="True">
<Setter Property="Background">
<Setter.Value>
<MultiBinding>
<MultiBinding.Converter>
<cv:MultiValueConverterPipe>
<cv:ColorBlendMultiConverter/>
<cv:ColorToBrushConverter/>
</cv:MultiValueConverterPipe>
</MultiBinding.Converter>
<Binding Path="(c:DIYGrid.Grid).SelectionHighlight" RelativeSource="{RelativeSource Self}"/>
<Binding Path="background"/>
</MultiBinding>
</Setter.Value>
</Setter>
<Setter Property="BorderBrush">
<Setter.Value>
<Binding Path="(c:DIYGrid.Grid).SelectionHighlight" RelativeSource="{RelativeSource Self}">
<Binding.Converter>
<cv:ValueConverterPipe>
<cv:ColorWithConverter A="255"/>
<cv:ColorToBrushConverter/>
</cv:ValueConverterPipe>
</Binding.Converter>
</Binding>
</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="RowHyperlinkCell" TargetType="c:HyperlinkCell" BasedOn="{StaticResource HyperlinkCellBase}">
<Setter Property="Padding" Value="{x:Static c:DIYGrid.AnimatableCellPadding}"/>
<Setter Property="CommandParameter"> <Setter Property="CommandParameter">
<Setter.Value> <Setter.Value>
<MultiBinding Converter="{x:Static pnl:PNLView.CellParamsConverter}"> <MultiBinding Converter="{x:Static pnl:PNLView.CellParamsConverter}">
@@ -403,24 +409,17 @@
</Setter> </Setter>
</Style> </Style>
<Style x:Key="HeaderRowHyperlinkCellBase" TargetType="c:HyperlinkCell"> <Style x:Key="HeaderRowHyperlinkCellBase" TargetType="c:HyperlinkCell" BasedOn="{StaticResource HyperlinkCellBase}">
<Setter Property="Background"> <!--
<Setter.Value> Note: the DIYGrid.Grid property serves as a proxy for the DIYGrid, because the header rows, unlike the regular rows/groups,
<SolidColorBrush Color="{Binding background}"/> are not visual children of the DIYGrid, and cannot access the grid with a RelativeSource.
</Setter.Value> Such a proxy allows the hyperlink cell base style triggers to display a hover brush that is a blend of the grid's SelectionHighlight color and the column's background.
</Setter>
<Setter Property="Foreground"> Caution: the fact that Element is used in this Setter.Value binding makes it precarious (if anyone renames _grid, this binding could silently break).
<Setter.Value> -->
<SolidColorBrush Color="{Binding foreground}"/> <Setter Property="c:DIYGrid.Grid" Value="{Binding ElementName=_grid}"/>
</Setter.Value>
</Setter>
<Setter Property="Margin" Value="0,0,0,1"/> <Setter Property="Margin" Value="0,0,0,1"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/> <Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="FontWeight" Value="{Binding font_weight}"/>
<Setter Property="FontSize" Value="{Binding font_size}"/>
<Setter Property="Text" Value="{Binding text}"/>
<Setter Property="Command" Value="{x:Static pnl:PNLView.CellClickCommand}"/>
<Setter Property="CommandTarget" Value="{Binding RelativeSource={RelativeSource AncestorType=pnl:PNLView}}"/>
<Setter Property="c:DIYGrid.ObservedCachedColumnParams"> <Setter Property="c:DIYGrid.ObservedCachedColumnParams">
<Setter.Value> <Setter.Value>
<x:Array Type="{x:Type c:CachedColumnParam}"> <x:Array Type="{x:Type c:CachedColumnParam}">
@@ -454,23 +453,7 @@
</Setter> </Setter>
</Style> </Style>
<Style x:Key="GroupRowHyperlinkCell" TargetType="c:HyperlinkCell"> <Style x:Key="GroupRowHyperlinkCell" TargetType="c:HyperlinkCell" BasedOn="{StaticResource HyperlinkCellBase}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding background}"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{Binding foreground}"/>
</Setter.Value>
</Setter>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="FontWeight" Value="{Binding font_weight}"/>
<Setter Property="FontSize" Value="{Binding font_size}"/>
<Setter Property="Text" Value="{Binding text}"/>
<Setter Property="Command" Value="{x:Static pnl:PNLView.CellClickCommand}"/>
<Setter Property="CommandTarget" Value="{Binding RelativeSource={RelativeSource AncestorType=pnl:PNLView}}"/>
<Setter Property="CommandParameter"> <Setter Property="CommandParameter">
<Setter.Value> <Setter.Value>
<MultiBinding Converter="{x:Static pnl:PNLView.CellParamsConverter}"> <MultiBinding Converter="{x:Static pnl:PNLView.CellParamsConverter}">
@@ -506,7 +489,7 @@
<Grid <Grid
c:DIYGrid.SyncWithColumnGeometrySource="{Binding ElementName=_grid}" c:DIYGrid.SyncWithColumnGeometrySource="{Binding ElementName=_grid}"
c:DIYGrid.SyncWithColumnGeometry="True" c:DIYGrid.SyncWithColumnGeometry="True"
Height="{Binding RowHeight, ElementName=_grid}" Height="{Binding RowHeight, ElementName=_grid, Converter={x:Static pnl:PNLView.HeaderRowHeightConverter}}"
> >
<Grid.Visibility> <Grid.Visibility>
<Binding Path="header_row_display"> <Binding Path="header_row_display">
@@ -559,7 +542,7 @@
<Grid <Grid
c:DIYGrid.SyncWithColumnGeometrySource="{Binding ElementName=_grid}" c:DIYGrid.SyncWithColumnGeometrySource="{Binding ElementName=_grid}"
c:DIYGrid.SyncWithColumnGeometry="True" c:DIYGrid.SyncWithColumnGeometry="True"
Height="{Binding RowHeight, ElementName=_grid}" Height="{Binding RowHeight, ElementName=_grid, Converter={x:Static pnl:PNLView.HeaderRowHeightConverter}}"
> >
<Grid.Visibility> <Grid.Visibility>
<Binding Path="header_row_display"> <Binding Path="header_row_display">
@@ -609,7 +592,6 @@
c:DIYGrid.CachedColumnParamsContainer="{Binding RelativeSource={RelativeSource AncestorType=pnl:PNLView}}" c:DIYGrid.CachedColumnParamsContainer="{Binding RelativeSource={RelativeSource AncestorType=pnl:PNLView}}"
VirtualizingPanel.ScrollUnit="Pixel" VirtualizingPanel.ScrollUnit="Pixel"
ScrollViewer.CanContentScroll="True" ScrollViewer.CanContentScroll="True"
RowHeight="24"
Rows="{Binding rows_view}" Rows="{Binding rows_view}"
SelectionHighlight="{Binding selection_highlight}" SelectionHighlight="{Binding selection_highlight}"
SupportGroupItems="True" SupportGroupItems="True"
@@ -1053,7 +1035,7 @@
<!--Row Template--> <!--Row Template-->
<c:DIYGrid.RowTemplate> <c:DIYGrid.RowTemplate>
<DataTemplate> <DataTemplate>
<Grid c:DIYGrid.SyncWithColumnGeometry="True" usp:GridAnimation.RowAnimation="{Binding animations}"> <Grid c:DIYGrid.SyncWithColumnGeometry="True" usp:GridAnimation.RowAnimation="{Binding animations}" Height="{Binding RowHeight, RelativeSource={RelativeSource AncestorType=c:DIYGrid}}">
<Grid.Background> <Grid.Background>
<SolidColorBrush Color="{Binding DataContext.grid_background_color, RelativeSource={RelativeSource AncestorType=pnl:PNLView}}"/> <SolidColorBrush Color="{Binding DataContext.grid_background_color, RelativeSource={RelativeSource AncestorType=pnl:PNLView}}"/>
</Grid.Background> </Grid.Background>
@@ -1147,7 +1129,7 @@
</VisualStateGroup> </VisualStateGroup>
</VisualStateManager.VisualStateGroups> </VisualStateManager.VisualStateGroups>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="{Binding RowHeight, RelativeSource={RelativeSource AncestorType=c:DIYGrid}, Converter={StaticResource GridLengthPixelConverter}}"/> <RowDefinition Height="{Binding RowHeight, RelativeSource={RelativeSource AncestorType=c:DIYGrid}, Converter={StaticResource GroupRowHeightConverter}}"/>
<RowDefinition Height="*"/> <RowDefinition Height="*"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Rectangle Grid.ColumnSpan="99" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stroke="Gray" StrokeThickness="1"/> <Rectangle Grid.ColumnSpan="99" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stroke="Gray" StrokeThickness="1"/>
@@ -1217,4 +1199,4 @@
<Rectangle Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="1" Fill="Gray"/> <Rectangle Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="1" Fill="Gray"/>
</Grid> </Grid>
</AdornerDecorator> </AdornerDecorator>
</UserControl> </UserControl>
@@ -4,8 +4,8 @@ using mbts.collections;
using mbts.spark; using mbts.spark;
using mbts.ui; using mbts.ui;
using mbts.ui.controls; using mbts.ui.controls;
using mbts.ui.controls.adorners;
using mbts.ui.converters; using mbts.ui.converters;
using mbts.ui.dpi;
using mbts.ui.extensions; using mbts.ui.extensions;
using mbts.ui.spark; using mbts.ui.spark;
using mbts.ui.utility; using mbts.ui.utility;
@@ -14,9 +14,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.ComponentModel; using System.ComponentModel;
using System.Dynamic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
@@ -31,6 +29,11 @@ namespace bts.shell.pnl {
} }
partial class PNLView : UserControl { partial class PNLView : UserControl {
public static readonly double
MinGroupRowHeight = 24.0.RoundLayoutValue(),
MinHeaderRowHeight = 24.0.RoundLayoutValue();
DIYGridPopupManager _popup_man_backing;
public enum Columns { public enum Columns {
Account = 1, Account = 1,
// Security // Security
@@ -85,6 +88,7 @@ namespace bts.shell.pnl {
public static readonly IValueConverter public static readonly IValueConverter
IncrementalGroupLevelConverter = ValueConverter.create<int, int>(level => level + 1), IncrementalGroupLevelConverter = ValueConverter.create<int, int>(level => level + 1),
GroupLevelMarginConverter = ValueConverter.create<int, Thickness>(level => new Thickness(24 * level, 0, 0, 0)), GroupLevelMarginConverter = ValueConverter.create<int, Thickness>(level => new Thickness(24 * level, 0, 0, 0)),
HeaderRowHeightConverter = new RangeBlockConverter<double> { Minimum = MinHeaderRowHeight },
ExpandedVisualStateConverter = ValueConverter.create<bool, string>(is_expanded => is_expanded ? "Expanded" : "Collapsed"); ExpandedVisualStateConverter = ValueConverter.create<bool, string>(is_expanded => is_expanded ? "Expanded" : "Collapsed");
public static readonly IMultiValueConverter public static readonly IMultiValueConverter
@@ -163,17 +167,22 @@ namespace bts.shell.pnl {
void _grid_loaded(object sender, RoutedEventArgs e) { void _grid_loaded(object sender, RoutedEventArgs e) {
// this is a hack to make room for the 'totals row' between the column headers and the regular rows. // this is a hack to make room for the 'totals row' between the column headers and the regular rows.
if (_grid.try_find_descendent_of_type(out DIYGridRowsPresenter rp)) { if (_grid.try_find_descendent_of_type(out DIYGridRowsPresenter rp)) {
rp.SetBinding(MarginProperty, new Binding(nameof(PNLVM.header_row_display)) { rp.SetBinding(MarginProperty,
Converter = ValueConverter.create<PNLHeaderRowDisplay, Thickness>(hrd => { BindingHelper.create_multi(
double top = 0; ValueConverter.create<PNLHeaderRowDisplay, double, Thickness>((hrd, row_height) => {
if ((hrd & PNLHeaderRowDisplay.Total) != 0) double top = 0;
top += 24; if ((hrd & PNLHeaderRowDisplay.Total) != 0)
if ((hrd & PNLHeaderRowDisplay.SelectedTotal) != 0) top += row_height;
top += 24; if ((hrd & PNLHeaderRowDisplay.SelectedTotal) != 0)
return new Thickness(0, top, 0, 0); top += row_height;
}), return new Thickness(0, top, 0, 0);
Source = DataContext }),
}); new Binding(nameof(PNLVM.header_row_display)),
new Binding {
Path = new PropertyPath(DIYGrid.RowHeightProperty),
Converter = HeaderRowHeightConverter,
Source = _grid
}));
} }
} }
#endregion #endregion
@@ -240,6 +249,15 @@ namespace bts.shell.pnl {
} }
#endregion #endregion
DIYGridPopupManager _popup_man {
get {
if (_popup_man_backing == null) {
_popup_man_backing = DIYGridPopupManager.create(this);
}
return _popup_man_backing;
}
}
void _cell_click(PNLCell cell) { void _cell_click(PNLCell cell) {
Log.Ui.info($"PNLCell Click: {cell}."); Log.Ui.info($"PNLCell Click: {cell}.");
try { try {
@@ -357,41 +375,20 @@ namespace bts.shell.pnl {
} }
} }
async void _show_auxiliary_popup<T>(T content, string context_desc, string title_desc, Color fg) { void _show_auxiliary_popup<T>(T content, string context_desc, string title_desc, Color fg) {
// vm var view = new HeaderedContentControl {
dynamic header = new ExpandoObject();
header.context = context_desc;
header.title = title_desc;
header.title_foreground = fg;
header.keep_open = false;
// view
var view = new PNLAuxiliaryPopupView {
Content = content, Content = content,
Header = header, Header = new AuxiliaryDataHeader {
context = context_desc,
title = title_desc,
title_foreground = fg
},
HorizontalAlignment = HorizontalAlignment.Left, HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top VerticalAlignment = VerticalAlignment.Top,
Resources = new AuxiliaryDataResources()
}; };
await Task.Delay(100); // Wait for obvm to load rows collection before showing UI to avoid a flash view.Style = view.Resources[AuxiliaryDataResources.PopupChildStyleKey] as Style;
view.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); _popup_man.show_async(view).ignore();
// popup adorner
// tho unlikely, better not assume target cell is non-null
var target_cell = _grid.ChildAtPoint<HyperlinkCell>(Mouse.GetPosition(_grid));
var popup_adorner = new PopupAdorner(_grid, target_cell ?? (FrameworkElement)_grid, view, HorizontalPosition.Middle, VerticalPosition.Bottom, 0, 0) {
OpenRelativeToMouse = target_cell == null,
EnableDragMove = true,
ClipToBounds = true
};
popup_adorner.SetBinding(PopupAdorner.StaysOpenProperty, new Binding("keep_open") { Source = header });
popup_adorner.PopupElement.InputBindings.Add(new KeyBinding(ApplicationCommands.Close, Key.Escape, ModifierKeys.None));
popup_adorner.PopupElement.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (s, e) => {
Log.assert(popup_adorner != null);
popup_adorner.detach();
popup_adorner = null;
}));
popup_adorner.attach();
popup_adorner.IsOpen = true;
FocusManager.SetIsFocusScope(popup_adorner.PopupElement, true);
popup_adorner.AdornedElement.Focus();
} }
class PNLGroupDescription : PropertyGroupDescription, IEquatable<PNLGroupDescription> { class PNLGroupDescription : PropertyGroupDescription, IEquatable<PNLGroupDescription> {
+1
View File
@@ -41,6 +41,7 @@
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DoubleMinMaxFilterControl.xaml"/> <ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DoubleMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DiscreteValuesFilterControl.xaml"/> <ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DiscreteValuesFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/TimeFilterControl.xaml"/> <ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/TimeFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/ActionMenu/ActionMenu.xaml"/>
<ResourceDictionary Source="/Modules/Spreader/ExecutionStrategyEditor.xaml"/> <ResourceDictionary Source="/Modules/Spreader/ExecutionStrategyEditor.xaml"/>
<ResourceDictionary Source="/view/Controls/Order/AlgoContentTemplateSelector.xaml"/> <ResourceDictionary Source="/view/Controls/Order/AlgoContentTemplateSelector.xaml"/>
<ResourceDictionary Source="/view/Controls/Order/AlgoPickerNodeView.xaml"/> <ResourceDictionary Source="/view/Controls/Order/AlgoPickerNodeView.xaml"/>
@@ -70,5 +70,21 @@ namespace mbts.ui {
}, () => Disposable.dispose(ref can_execute_sub)); }, () => Disposable.dispose(ref can_execute_sub));
return cmd; return cmd;
} }
public static ICommand create<T, TResult>(Action<TResult> execute, Func<T, bool> get_can_execute, Func<T, TResult> convert, out IObserver<T> observer) {
TResult param = default;
bool can_execute = false;
var cmd = new DelegateCommand(() => execute(param), () => can_execute);
IDisposable can_execute_sub = null;
observer = new AnonymousObserver<T>(val => {
var could_execute = can_execute;
can_execute = get_can_execute(val);
if (can_execute)
param = convert(val);
if (can_execute != could_execute)
cmd.RaiseCanExecuteChanged();
}, () => Disposable.dispose(ref can_execute_sub));
return cmd;
}
} }
} }
@@ -34,6 +34,9 @@ namespace mbts {
public static bool IsNaNOrInfinity(double d) => double.IsNaN(d) || double.IsInfinity(d); public static bool IsNaNOrInfinity(double d) => double.IsNaN(d) || double.IsInfinity(d);
public static bool IsNaNOrInfinityOr(double d, params double[] values) => IsNaNOrInfinity(d) || values.Contains(d); public static bool IsNaNOrInfinityOr(double d, params double[] values) => IsNaNOrInfinity(d) || values.Contains(d);
public static bool IsOneOf(double d, params double[] values) => values.Contains(d); public static bool IsOneOf(double d, params double[] values) => values.Contains(d);
// TODO: replace refs to IsNaNOrInfinity with IsReal (it's a shorter name, and just as expressive)
public static bool IsReal(this double d) => !double.IsNaN(d) && !double.IsInfinity(d);
public static bool IsRealNonZero(this double d) => d != 0 && !double.IsNaN(d) && !double.IsInfinity(d);
public static double CoerceNaN(double value) => CoerceNaN(value, 0.0); public static double CoerceNaN(double value) => CoerceNaN(value, 0.0);
public static double CoerceNaN(double value, double if_nan) => double.IsNaN(value) ? if_nan : value; public static double CoerceNaN(double value, double if_nan) => double.IsNaN(value) ? if_nan : value;
public static double CoerceNaNOrInfinity(double value) => CoerceNaNOrInfinity(value, 0.0); public static double CoerceNaNOrInfinity(double value) => CoerceNaNOrInfinity(value, 0.0);
@@ -131,6 +131,11 @@ namespace mbts.ui.native
[DllImport("user32.dll")] [DllImport("user32.dll")]
public static extern bool GetCursorPos(out Win32Point pt); public static extern bool GetCursorPos(out Win32Point pt);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
public static readonly IntPtr HWND_TOP = new IntPtr(0);
public static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
[DllImport("user32.dll")] [DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwnd_insert_after, int x, int y, int cx, int cy, SWP flags); public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwnd_insert_after, int x, int y, int cx, int cy, SWP flags);
@@ -236,6 +241,8 @@ namespace mbts.ui.native
[DllImport("user32")] [DllImport("user32")]
public static extern bool IsWindow(IntPtr handle); public static extern bool IsWindow(IntPtr handle);
[DllImport("user32", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool ShowWindow(HandleRef hWnd, int nCmdShow);
} }
@@ -250,12 +257,42 @@ namespace mbts.ui.native
TRANSPARENT = 0x20 TRANSPARENT = 0x20
} }
public enum SW {
SW_HIDE = 0x0000,
SW_SHOWNORMAL = 0x0001,
SW_SHOWMINIMIZED = 0x0002,
SW_MAXIMIZE = 0x0003,
SW_SHOWNOACTIVATE = 0x0004,
SW_SHOW = 0x0005,
SW_MINIMIZE = 0x0006,
SW_SHOWMINNOACTIVATE = 0x0007,
SW_SHOWNA = 0x0008,
SW_RESTORE = 0x0009,
SW_SHOWDEFAULT = 0x000A,
SW_FORCEMINIMIZE = 0x000B,
}
[Flags] [Flags]
public enum SWP : uint public enum SWP : uint
{ {
SWP_NOSIZE = 1, SWP_NOSIZE = 1,
SWP_NOMOVE = 2, SWP_NOMOVE = 2,
SWP_FRAMECHANGED = 0x20 SWP_NOZORDER = 0x0004,
SWP_NOREDRAW = 0x0008,
SWP_NOACTIVATE = 0x0010,
// The frame changed: send WM_NCCALCSIZE
SWP_FRAMECHANGED = 0x0020,
SWP_SHOWWINDOW = 0x0040,
SWP_HIDEWINDOW = 0x0080,
SWP_NOCOPYBITS = 0x0100,
// Don’t do owner Z ordering
SWP_NOOWNERZORDER = 0x0200,
// Don’t send WM_WINDOWPOSCHANGING
SWP_NOSENDCHANGING = 0x0400,
SWP_ASYNCWINDOWPOS = 0x4000,
TOPMOST_FLAGS = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING,
POP_TOPMOST_FLAGS = SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING
} }
public enum SPI : uint public enum SPI : uint
@@ -138,6 +138,7 @@ namespace mbts.ui.native
NCMBUTTONDOWN = 0x00A7, NCMBUTTONDOWN = 0x00A7,
NCMBUTTONUP = 0x00A8, NCMBUTTONUP = 0x00A8,
NCMOUSEMOVE = 0x00A0, NCMOUSEMOVE = 0x00A0,
NCMOUSELEAVE = 0x02A2,
NCPAINT = 0x0085, NCPAINT = 0x0085,
NCRBUTTONDBLCLK = 0x00A6, NCRBUTTONDBLCLK = 0x00A6,
NCRBUTTONDOWN = 0x00A4, NCRBUTTONDOWN = 0x00A4,
@@ -15,6 +15,7 @@ namespace bts.settings {
// determine the various windows to which such rules apply. // determine the various windows to which such rules apply.
interface IFillsGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { } interface IFillsGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IMarketViewGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { } interface IMarketViewGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface ITimeAndSalesGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IPAndLGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { } interface IPAndLGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IPNLSettingsMigrationRule : ISettingsMigrationRule<PNLSettings> { } interface IPNLSettingsMigrationRule : ISettingsMigrationRule<PNLSettings> { }
interface ISyntheticManagementMigrationRule : ISettingsMigrationRule<GridSettings> { } interface ISyntheticManagementMigrationRule : ISettingsMigrationRule<GridSettings> { }
@@ -26,7 +26,8 @@ namespace mbts.persist {
_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.fills_grid, (us, gs) => us.with(provided_fills_gridsettings: gs)), _fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.fills_grid, (us, gs) => us.with(provided_fills_gridsettings: gs)),
_mview_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.market_view_grid, (us, gs) => us.with(provided_market_view_gridsettings: gs)), _mview_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.market_view_grid, (us, gs) => us.with(provided_market_view_gridsettings: gs)),
_pandl_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.pnl_grid, (us, gs) => us.with(provided_pnl_gridsettings: gs)), _pandl_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.pnl_grid, (us, gs) => us.with(provided_pnl_gridsettings: gs)),
_synth_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.synthetic_management_grid, (us, gs) => us.with(provided_synthetic_management_gridsettings: gs)); _synth_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.synthetic_management_grid, (us, gs) => us.with(provided_synthetic_management_gridsettings: gs)),
_time_and_sales_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.time_and_sales_grid, (us, gs) => us.with(time_and_sales: gs));
static readonly IImmutableProperty<UserSettings, PNLSettings> static readonly IImmutableProperty<UserSettings, PNLSettings>
_pnl_propi = ImmutableProperty.create<UserSettings, PNLSettings>(us => us.pnl, (us, pnl) => us.with(pnl: pnl)); _pnl_propi = ImmutableProperty.create<UserSettings, PNLSettings>(us => us.pnl, (us, pnl) => us.with(pnl: pnl));
@@ -38,6 +39,7 @@ namespace mbts.persist {
readonly IEnumerable<IPAndLGridSettingsMigrationRule> _pandl_migration_rules; readonly IEnumerable<IPAndLGridSettingsMigrationRule> _pandl_migration_rules;
readonly IEnumerable<IPNLSettingsMigrationRule> _pnl_migration_rules; readonly IEnumerable<IPNLSettingsMigrationRule> _pnl_migration_rules;
readonly IEnumerable<ISyntheticManagementMigrationRule> _synth_migration_rules; readonly IEnumerable<ISyntheticManagementMigrationRule> _synth_migration_rules;
readonly IEnumerable<ITimeAndSalesGridSettingsMigrationRule> _time_and_sales_migration_rules;
readonly IUserPersist _persist; readonly IUserPersist _persist;
UserSettings _default_settings; UserSettings _default_settings;
@@ -49,7 +51,8 @@ namespace mbts.persist {
[ImportMany]IEnumerable<IMarketViewGridSettingsMigrationRule> mview_migration_rules, [ImportMany]IEnumerable<IMarketViewGridSettingsMigrationRule> mview_migration_rules,
[ImportMany]IEnumerable<IPAndLGridSettingsMigrationRule> pandl_migration_rules, [ImportMany]IEnumerable<IPAndLGridSettingsMigrationRule> pandl_migration_rules,
[ImportMany]IEnumerable<IPNLSettingsMigrationRule> pnl_migration_rules, [ImportMany]IEnumerable<IPNLSettingsMigrationRule> pnl_migration_rules,
[ImportMany]IEnumerable<ISyntheticManagementMigrationRule> synth_migration_rules) { [ImportMany]IEnumerable<ISyntheticManagementMigrationRule> synth_migration_rules,
[ImportMany]IEnumerable<ITimeAndSalesGridSettingsMigrationRule> time_and_sales_migration_rules) {
// //
_persist = persist; _persist = persist;
_fills_migration_rules = fills_migration_rules ?? Enumerable.Empty<IFillsGridSettingsMigrationRule>(); _fills_migration_rules = fills_migration_rules ?? Enumerable.Empty<IFillsGridSettingsMigrationRule>();
@@ -57,6 +60,7 @@ namespace mbts.persist {
_pandl_migration_rules = pandl_migration_rules ?? Enumerable.Empty<IPAndLGridSettingsMigrationRule>(); _pandl_migration_rules = pandl_migration_rules ?? Enumerable.Empty<IPAndLGridSettingsMigrationRule>();
_pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty<IPNLSettingsMigrationRule>(); _pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty<IPNLSettingsMigrationRule>();
_synth_migration_rules = synth_migration_rules ?? Enumerable.Empty<ISyntheticManagementMigrationRule>(); _synth_migration_rules = synth_migration_rules ?? Enumerable.Empty<ISyntheticManagementMigrationRule>();
_time_and_sales_migration_rules = time_and_sales_migration_rules ?? Enumerable.Empty<ITimeAndSalesGridSettingsMigrationRule>();
init(); init();
async void init() { async void init() {
UserSettings s; UserSettings s;
@@ -68,7 +72,8 @@ namespace mbts.persist {
_mview_migration_rules.merge().wrap(_mview_propi), _mview_migration_rules.merge().wrap(_mview_propi),
_pandl_migration_rules.merge().wrap(_pandl_propi), _pandl_migration_rules.merge().wrap(_pandl_propi),
_pnl_migration_rules.merge().wrap(_pnl_propi), _pnl_migration_rules.merge().wrap(_pnl_propi),
_synth_migration_rules.merge().wrap(_synth_propi) _synth_migration_rules.merge().wrap(_synth_propi),
_time_and_sales_migration_rules.merge().wrap(_time_and_sales_propi)
}; };
SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules); SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules);
// TODO: move ladder sanitization logic into ISettingsMigrationRule // TODO: move ladder sanitization logic into ISettingsMigrationRule
@@ -148,6 +153,12 @@ namespace mbts.persist {
_synth_migration_rules, _synth_migration_rules,
_synth_propi); _synth_propi);
public IWindowSettingsManager<GridSettings> create_time_and_sales_settings_manager(GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_time_and_sales_migration_rules,
_time_and_sales_propi);
public async Task save_default(UserSettings value) { public async Task save_default(UserSettings value) {
// notify observers before persisting so the changes are reflected immediately in the ui // notify observers before persisting so the changes are reflected immediately in the ui
lock (_default_settings_lock) { lock (_default_settings_lock) {
+15 -1
View File
@@ -5,9 +5,23 @@
xmlns:ui="clr-namespace:mbts.ui" xmlns:ui="clr-namespace:mbts.ui"
> >
<!--Control Base Colors--> <!--Control Base Colors-->
<Color x:Key="Control.SuperLightGrayColor">#F6F6F6</Color>
<Color x:Key="Control.LightGrayColor">#E5E5E5</Color>
<Color x:Key="Control.LightMediumGrayColor">#CFCFCF</Color>
<Color x:Key="Control.MediumGrayColor">#B3B3B3</Color> <Color x:Key="Control.MediumGrayColor">#B3B3B3</Color>
<Color x:Key="Control.MediumDarkGrayColor">#ACACAC</Color>
<Color x:Key="Control.AlphaLightGrayColor">#10000000</Color>
<Color x:Key="Control.AlphaLightMediumGrayColor">#24000000</Color>
<Color x:Key="Control.AlphaMediumGrayColor">#3A000000</Color>
<Color x:Key="Control.AlphaMediumGrayColor2">#FF0000</Color>
<Color x:Key="Control.DarkMediumGrayColor">#FF959595</Color>
<Color x:Key="Control.DarkGrayColor">#707070</Color>
<Color x:Key="Text.Prompt.Foreground.Color">#FF999999</Color> <Color x:Key="Text.Prompt.Foreground.Color">#FF999999</Color>
<SolidColorBrush x:Key="Control.AlphaLightGrayBrush" Color="{StaticResource Control.AlphaLightGrayColor}"/>
<SolidColorBrush x:Key="Control.AlphaLightMediumGrayBrush" Color="{StaticResource Control.AlphaLightMediumGrayColor}"/>
<SolidColorBrush x:Key="Control.LightGrayBrush" Color="{StaticResource Control.LightGrayColor}"/>
<SolidColorBrush x:Key="Control.LightMediumGrayBrush" Color="{StaticResource Control.LightMediumGrayColor}"/>
<SolidColorBrush x:Key="Control.MediumGrayBrush" Color="{StaticResource Control.MediumGrayColor}"/> <SolidColorBrush x:Key="Control.MediumGrayBrush" Color="{StaticResource Control.MediumGrayColor}"/>
<SolidColorBrush x:Key="CommonBackground" Color="{ui:BTSColor common_background}" /> <SolidColorBrush x:Key="CommonBackground" Color="{ui:BTSColor common_background}" />
<SolidColorBrush x:Key="ControlBackground" Color="{x:Static mbts:BTSColors.common_background}" /> <SolidColorBrush x:Key="ControlBackground" Color="{x:Static mbts:BTSColors.common_background}" />
@@ -130,4 +144,4 @@
<SolidColorBrush x:Key="ListBoxItem.Selected.Inactive.Border" Color="{StaticResource ListBoxItem.Selected.Inactive.Border.Color}"/> <SolidColorBrush x:Key="ListBoxItem.Selected.Inactive.Border" Color="{StaticResource ListBoxItem.Selected.Inactive.Border.Color}"/>
<SolidColorBrush x:Key="ListBoxItem.MouseOver.Background" Color="{StaticResource ListBoxItem.MouseOver.Background.Color}"/> <SolidColorBrush x:Key="ListBoxItem.MouseOver.Background" Color="{StaticResource ListBoxItem.MouseOver.Background.Color}"/>
<SolidColorBrush x:Key="ListBoxItem.MouseOver.Border" Color="{StaticResource ListBoxItem.MouseOver.Border.Color}"/> <SolidColorBrush x:Key="ListBoxItem.MouseOver.Border" Color="{StaticResource ListBoxItem.MouseOver.Border.Color}"/>
</ResourceDictionary> </ResourceDictionary>
@@ -1,78 +1,102 @@
<c:PopupControl <ResourceDictionary
x:Class="mbts.ui.controls.ActionMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls" xmlns:c="clr-namespace:mbts.ui.controls"
Margin="1" xmlns:cv="clr-namespace:mbts.ui.converters"
Background="Transparent"
BorderBrush="Transparent"
Padding="2"
PopupPlacement="Bottom"
ShowExpanderArrow="False"
Cursor="Hand"
> >
<c:PopupControl.Resources> <SolidColorBrush x:Key="SeparatorFill" Color="{DynamicResource Control.AlphaMediumGrayColor}"/>
<CollectionViewSource x:Key="ItemsSourceView" Source="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=c:ActionMenu}}">
<CollectionViewSource.GroupDescriptions> <ControlTemplate x:Key="ActionMenuTemplate" TargetType="c:ActionMenu">
<PropertyGroupDescription PropertyName="group"/> <Border
</CollectionViewSource.GroupDescriptions> HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
</CollectionViewSource> VerticalAlignment="{TemplateBinding VerticalAlignment}"
</c:PopupControl.Resources> Width="{TemplateBinding Width}"
<c:PopupControl.Header> Height="{TemplateBinding Height}"
<Border Width="16"> >
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:MouseStateDefinition MouseSource="{Binding Group.Target, RelativeSource={RelativeSource Self}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal"/>
<VisualState Name="MouseOver" Storyboard="{DynamicResource Button.MouseOver.Storyboard}"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid> <Grid>
<Grid.RowDefinitions> <Button
<RowDefinition/> x:Name="button"
<RowDefinition/> Content="{TemplateBinding Header}"
<RowDefinition/> ContentTemplate="{TemplateBinding HeaderTemplate}"
</Grid.RowDefinitions> ContentTemplateSelector="{TemplateBinding HeaderTemplateSelector}"
<Rectangle Grid.Row="0" Fill="Black" Height="2" HorizontalAlignment="Stretch"/> HorizontalAlignment="Stretch"
<Rectangle Grid.Row="1" Fill="Black" Height="2" Margin="0,4,0,0" HorizontalAlignment="Stretch"/> VerticalAlignment="Stretch"
<Rectangle Grid.Row="2" Fill="Black" Height="2" Margin="0,4,0,0" HorizontalAlignment="Stretch"/> Padding="2.5,2"
Style="{DynamicResource SparkToolBarButton}"
>
<Button.Background>
<SolidColorBrush/>
</Button.Background>
</Button>
<Popup c:PopupViewController.ButtonSource="{Binding ElementName=button}" Placement="Bottom" PlacementTarget="{Binding ElementName=button}" StaysOpen="False">
<Border Background="{DynamicResource Control.LightGrayBrush}" BorderThickness="1">
<Border.BorderBrush>
<SolidColorBrush Color="{DynamicResource Control.DarkMediumGrayColor}"/>
</Border.BorderBrush>
<ItemsPresenter/>
</Border>
</Popup>
</Grid> </Grid>
</Border> </Border>
</c:PopupControl.Header> </ControlTemplate>
<Menu ItemsSource="{Binding Source={StaticResource ItemsSourceView}}">
<Menu.ItemsPanel> <DataTemplate x:Key="HamburgerButtonTemplate">
<ItemsPanelTemplate> <Image
<StackPanel Orientation="Vertical"/> HorizontalAlignment="Stretch"
</ItemsPanelTemplate> VerticalAlignment="Stretch"
</Menu.ItemsPanel> Source="{x:Static u:Icons.HamburgerMenu}"
<Menu.GroupStyle> />
<GroupStyle> </DataTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="GroupItem"> <Style x:Key="ActionMenuBase" TargetType="c:ActionMenu">
<Setter Property="Template"> <Setter Property="Background">
<Setter.Value> <Setter.Value>
<ControlTemplate TargetType="GroupItem"> <SolidColorBrush/>
<StackPanel> </Setter.Value>
<ItemsPresenter/> </Setter>
<Rectangle HorizontalAlignment="Stretch" Height="1" Margin="22,0,0,0" Fill="LightGray"/> <Setter Property="BorderBrush">
</StackPanel> <Setter.Value>
</ControlTemplate> <SolidColorBrush/>
</Setter.Value> </Setter.Value>
</Setter> </Setter>
</Style> <Setter Property="Template" Value="{StaticResource ActionMenuTemplate}"/>
</GroupStyle.ContainerStyle> </Style>
</GroupStyle>
</Menu.GroupStyle> <DataTemplate DataType="{x:Type u:MenuItemVM}">
<Menu.ItemContainerStyle> <TextBlock Text="{Binding}" VerticalAlignment="Center"/>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}"> </DataTemplate>
<!--NOTE: CommandParameter binding must be declared BEFORE Command,
otherwise, CanExecuted is called before the parameter value is realized...I know, it sucks...--> <Style TargetType="c:ActionMenu" BasedOn="{StaticResource ActionMenuBase}">
<Setter Property="CommandParameter" Value="{Binding parameter}"/> <Setter Property="Panel.ZIndex" Value="1"/>
<Setter Property="Command" Value="{Binding command}"/> <Setter Property="HorizontalAlignment" Value="Right"/>
<Setter Property="Header" Value="{Binding name}"/> <Setter Property="VerticalAlignment" Value="Top"/>
<Setter Property="HeaderTemplate"> <Setter Property="Margin" Value="1"/>
<Setter.Value> <Setter Property="HeaderTemplate" Value="{StaticResource HamburgerButtonTemplate}"/>
<DataTemplate> <Setter Property="Width" Value="22"/>
<TextBlock Text="{Binding}" VerticalAlignment="Center"/> <Setter Property="ItemContainerStyle">
</DataTemplate> <Setter.Value>
</Setter.Value> <Style TargetType="MenuItem">
</Setter> <Setter Property="MinWidth" Value="167"/>
<Setter Property="Icon" Value="{Binding icon, Converter={StaticResource IconConverter}}"/> <Setter Property="CommandParameter" Value="{Binding parameter}"/>
<Setter Property="MinWidth" Value="167"/> <Setter Property="Command" Value="{Binding command}"/>
</Style> <Setter Property="Header" Value="{Binding name}"/>
</Menu.ItemContainerStyle> <Setter Property="Icon" Value="{Binding icon, Converter={x:Static cv:ImageSourceIconConverter.Instance}}"/>
</Menu> </Style>
</c:PopupControl> </Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
@@ -1,22 +1,15 @@
using System.Collections; using System.Windows;
using System.Linq; using System.Windows.Controls;
using System.Windows;
namespace mbts.ui.controls { namespace mbts.ui.controls {
/// <summary> /// <summary>
/// Interaction logic for ActionMenu.xaml /// Interaction logic for ActionMenu.xaml
/// </summary> /// </summary>
partial class ActionMenu : PopupControl { class ActionMenu : HeaderedItemsControl {
public ActionMenu() => static ActionMenu() =>
InitializeComponent(); DefaultStyleKeyProperty.OverrideMetadata(typeof(ActionMenu), new FrameworkPropertyMetadata(typeof(ActionMenu)));
public static readonly DependencyProperty ItemsSourceProperty = protected override DependencyObject GetContainerForItemOverride() =>
WPFHelper.create_dp<IEnumerable, ActionMenu>( new MenuItem();
nameof(ItemsSource), Enumerable.Empty<IMenuItemVM>());
public IEnumerable ItemsSource {
get => GetValue(ItemsSourceProperty) as IEnumerable;
set => SetValue(ItemsSourceProperty, value);
}
} }
} }
@@ -0,0 +1,59 @@
using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace mbts.ui.controls.adorners {
class AdornerHost : Adorner {
UIElement _child;
public AdornerHost(UIElement adorned_element)
: base(adorned_element) { }
public static readonly DependencyProperty ChildProperty =
WPFHelper.create_dp<UIElement, AdornerHost>(
nameof(Child), (o, v) => {
if (o._child != null)
o.RemoveVisualChild(o._child);
o._child = v;
if (v != null)
o.AddVisualChild(v);
});
public UIElement Child {
get => _child;
set => SetValue(ChildProperty, value);
}
protected override int VisualChildrenCount => _child != null ? 1 : 0;
protected override Visual GetVisualChild(int index) =>
index == 0 && _child != null ? _child : throw new ArgumentOutOfRangeException();
protected override Size ArrangeOverride(Size finalSize) {
if (_child == null) {
return base.ArrangeOverride(finalSize);
}
_child.Arrange(new Rect(finalSize));
return _child.DesiredSize;
}
protected override Size MeasureOverride(Size constraint) {
if (_child == null) {
return base.MeasureOverride(constraint);
}
_child.Measure(constraint);
return _child.DesiredSize;
}
}
class AdornerHost<TChild> : AdornerHost where TChild : UIElement {
public AdornerHost(UIElement adorned_element)
: base(adorned_element) { }
public new TChild Child {
get => base.Child as TChild;
set => base.Child = value;
}
}
}
@@ -0,0 +1,136 @@
using mbts.ui.dpi;
using mbts.ui.extensions;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace mbts.ui.controls.adorners {
class DIYGridCellHoverAdorner : Adorner, IDisposable {
Brush _row_fill, _cell_fill;
Pen _row_stroke, _cell_stroke;
ScrollViewer _scroll_viewer;
ScrollContentPresenter _scroll_content;
DIYGrid _grid;
IDisposable _dispose;
DIYGrid.CellGeometry? _hover_cell;
AdornerHost _menu_host = null;
ActionMenu _menu => _menu_host.Child as ActionMenu;
#region RowFill
public static readonly DependencyProperty RowFillProperty =
WPFHelper.create_dp<Brush, DIYGridCellHoverAdorner>(
nameof(RowFill),
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._row_fill = v,
FrozenBrushCache.get_brush(DIYGrid.DefaultSelectionHighlight));
public SolidColorBrush RowFill {
get => GetValue(RowFillProperty) as SolidColorBrush;
set => SetValue(RowFillProperty, value);
}
#endregion
#region RowStroke
public static readonly DependencyProperty RowStrokeProperty =
WPFHelper.create_dp<Pen, DIYGridCellHoverAdorner>(
nameof(RowStroke),
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._row_stroke = v);
public Pen RowStroke {
get => GetValue(RowStrokeProperty) as Pen;
set => SetValue(RowStrokeProperty, value);
}
#endregion
#region CellFill
public static readonly DependencyProperty CellFillProperty =
WPFHelper.create_dp<Brush, DIYGridCellHoverAdorner>(
nameof(CellFill),
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._cell_fill = v);
public SolidColorBrush CellFill {
get => GetValue(CellFillProperty) as SolidColorBrush;
set => SetValue(CellFillProperty, value);
}
#endregion
#region CellStroke
public static readonly DependencyProperty CellStrokeProperty =
WPFHelper.create_dp<Pen, DIYGridCellHoverAdorner>(
nameof(CellStroke),
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._cell_stroke = v);
public Pen CellStroke {
get => GetValue(CellStrokeProperty) as Pen;
set => SetValue(CellStrokeProperty, value);
}
#endregion
public DIYGridCellHoverAdorner(ListBox list_box, ScrollViewer scroll_viewer)
: this(list_box, scroll_viewer, list_box.descendants_of_type<ScrollContentPresenter>().FirstOrDefault()) { }
/// <summary>
/// Create an instance of the <see cref="DIYGridCellHoverAdorner"/> class.
/// </summary>
/// <param name="list_box"></param>
/// <param name="scroll_viewer"></param>
/// <param name="scroll_content">
/// The actual AdornedElement (the ScrollViewer may clip the ScrollContentPresenter, and the most prudent way to reflect such a clip is to use it as the actual AdornedElement).
/// </param>
public DIYGridCellHoverAdorner(ListBox list_box, ScrollViewer scroll_viewer, ScrollContentPresenter scroll_content)
: base(scroll_content) {
_row_fill = RowFill;
_row_stroke = RowStroke;
_cell_fill = CellFill;
_cell_stroke = CellStroke;
_scroll_viewer = scroll_viewer;
_scroll_content = scroll_content;
IsHitTestVisible = false;
// reflect AdornedElement's clip
IsClipEnabled = true;
_grid = list_box.find_ancestor_of_type<DIYGrid>();
_dispose = Disposable.Create(
_grid.SubscribeMouseHoverCell().Subscribe(cell => {
_hover_cell = cell;
if (_hover_cell.HasValue) {
var (row, col) = _hover_cell.Value;
var row_tl = row.TranslatePoint(default, this);
}
InvalidateVisual();
}));
}
protected override void OnRender(DrawingContext drawingContext) {
base.OnRender(drawingContext);
if (_hover_cell.HasValue) {
(var row, var cell) = _hover_cell.Value;
if (row != null) {
var row_tl = new Lazy<Point>(() => row.TranslatePoint(default, this));
if (_row_fill != null || _row_stroke != null) {
var row_rect = new Rect(row_tl.Value, row.RenderSize);
if (_scroll_content != null) {
var content_bounds = this.GetChildBounds(_scroll_content);
row_rect.Intersect(content_bounds);
}
drawingContext.DrawRectangle(_row_fill, _row_stroke, row_rect, true);
}
if (_cell_fill != null || _cell_stroke != null) {
var cell_rect = cell.to_visible_rect(row.ActualHeight, row_tl.Value.Y);
drawingContext.DrawRectangle(_cell_fill, _cell_stroke, cell_rect, true);
}
}
}
}
public void Dispose() =>
Disposable.dispose(ref _dispose);
}
}
@@ -24,7 +24,7 @@ namespace mbts.ui.controls.adorners {
nameof(Fill), nameof(Fill),
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._fill = v, (o, v) => o._fill = v,
DIYGrid.DefaultSelectionHighlight); FrozenBrushCache.get_brush(DIYGrid.DefaultSelectionHighlight));
public SolidColorBrush Fill { public SolidColorBrush Fill {
get => GetValue(FillProperty) as SolidColorBrush; get => GetValue(FillProperty) as SolidColorBrush;
@@ -38,7 +38,7 @@ namespace mbts.ui.controls.adorners {
nameof(Stroke), nameof(Stroke),
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._stroke = v, (o, v) => o._stroke = v,
DIYGrid.DefaultSelectionStroke); FrozenPenCache.get_pen(DIYGrid.DefaultSelectionHighlight));
public Pen Stroke { public Pen Stroke {
get => GetValue(StrokeProperty) as Pen; get => GetValue(StrokeProperty) as Pen;
@@ -8,8 +8,8 @@ using System.Windows.Media;
namespace mbts.ui.controls.adorners { namespace mbts.ui.controls.adorners {
public class DragRectAdorner : Adorner, IDisposable { public class DragRectAdorner : Adorner, IDisposable {
Brush _fill = DIYGrid.DefaultSelectionHighlight; Brush _fill;
Pen _stroke = DIYGrid.DefaultSelectionStroke; Pen _stroke;
readonly ScrollViewerTuple _scroll_viewer_tup; readonly ScrollViewerTuple _scroll_viewer_tup;
readonly double _drift_multiplier; readonly double _drift_multiplier;
Point? _drag_start; Point? _drag_start;
@@ -20,7 +20,7 @@ namespace mbts.ui.controls.adorners {
nameof(Fill), nameof(Fill),
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._fill = v, (o, v) => o._fill = v,
DIYGrid.DefaultSelectionHighlight); FrozenBrushCache.get_brush(DIYGrid.DefaultSelectionHighlight));
public SolidColorBrush Fill { public SolidColorBrush Fill {
get => GetValue(FillProperty) as SolidColorBrush; get => GetValue(FillProperty) as SolidColorBrush;
@@ -32,7 +32,7 @@ namespace mbts.ui.controls.adorners {
nameof(Stroke), nameof(Stroke),
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._stroke = v, (o, v) => o._stroke = v,
DIYGrid.DefaultSelectionStroke); FrozenPenCache.get_pen(DIYGrid.DefaultSelectionHighlight));
public Pen Stroke { public Pen Stroke {
get => GetValue(StrokeProperty) as Pen; get => GetValue(StrokeProperty) as Pen;
@@ -48,6 +48,8 @@ namespace mbts.ui.controls.adorners {
/// <param name="scroll_viewer">The element's ScrollViewer.</param> /// <param name="scroll_viewer">The element's ScrollViewer.</param>
/// <param name="drift_multiplier">The number of pixels per scroll unit.</param> /// <param name="drift_multiplier">The number of pixels per scroll unit.</param>
public DragRectAdorner(FrameworkElement adorned_element, ScrollViewer scroll_viewer = null, double drift_multiplier = 1) : base(adorned_element) { public DragRectAdorner(FrameworkElement adorned_element, ScrollViewer scroll_viewer = null, double drift_multiplier = 1) : base(adorned_element) {
_fill = Fill;
_stroke = Stroke;
_drift_multiplier = drift_multiplier; _drift_multiplier = drift_multiplier;
AdornedElement.PreviewMouseDown += _on_preview_mouse_down; AdornedElement.PreviewMouseDown += _on_preview_mouse_down;
AdornedElement.PreviewMouseMove += _on_preview_mouse_move; AdornedElement.PreviewMouseMove += _on_preview_mouse_move;
@@ -1,22 +1,18 @@
using System; using mbts.ui.extensions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Documents; using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using bts.utils;
using mbts.ui.extensions;
namespace mbts.ui.controls.adorners { namespace mbts.ui.controls.adorners {
public class RowSelectionAdorner : Adorner, DIYGrid.ISelectionHighlightListener, IDisposable { class RowSelectionAdorner : Adorner, IDisposable {
Brush _fill = DIYGrid.DefaultSelectionHighlight; Brush _fill;
Pen _stroke = DIYGrid.DefaultSelectionStroke; Pen _stroke;
ListBox _diy_rp;
DIYGridRowsPresenter _diy_rp;
ScrollViewer _diy_scroll; ScrollViewer _diy_scroll;
ScrollContentPresenter _diy_scp;
List<IDisposable> _disposables = new List<IDisposable>(); List<IDisposable> _disposables = new List<IDisposable>();
#region Fill #region Fill
@@ -25,20 +21,21 @@ namespace mbts.ui.controls.adorners {
nameof(Fill), nameof(Fill),
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._fill = v, (o, v) => o._fill = v,
DIYGrid.DefaultSelectionHighlight); FrozenBrushCache.get_brush(DIYGrid.DefaultSelectionHighlight));
public SolidColorBrush Fill { public SolidColorBrush Fill {
get => GetValue(FillProperty) as SolidColorBrush; get => GetValue(FillProperty) as SolidColorBrush;
set => SetValue(FillProperty, value); set => SetValue(FillProperty, value);
} }
#endregion #endregion
#region Stroke #region Stroke
public static readonly DependencyProperty StrokeProperty = public static readonly DependencyProperty StrokeProperty =
WPFHelper.create_dp<Pen, RowSelectionAdorner>( WPFHelper.create_dp<Pen, RowSelectionAdorner>(
nameof(Stroke), nameof(Stroke),
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._stroke = v, (o, v) => o._stroke = v,
DIYGrid.DefaultSelectionStroke); FrozenPenCache.get_pen(DIYGrid.DefaultSelectionHighlight.with(255)));
public Pen Stroke { public Pen Stroke {
get => GetValue(StrokeProperty) as Pen; get => GetValue(StrokeProperty) as Pen;
@@ -46,13 +43,28 @@ namespace mbts.ui.controls.adorners {
} }
#endregion #endregion
internal RowSelectionAdorner(DIYGridRowsPresenter adorned_element, ScrollViewer scroll_viewer) : base(adorned_element) { public RowSelectionAdorner(ListBox list_box, ScrollViewer scroll_viewer)
: this(list_box, scroll_viewer, list_box.descendants_of_type<ScrollContentPresenter>().FirstOrDefault()) { }
/// <summary>
/// Create an instance of the <see cref="RowSelectionAdorner"/> class.
/// </summary>
/// <param name="list_box"></param>
/// <param name="scroll_viewer"></param>
/// <param name="scroll_presenter">
/// The actual AdornedElement (the ScrollViewer may clip the ScrollContentPresenter, and the most prudent way to reflect such a clip is to use it as the actual AdornedElement).
/// </param>
public RowSelectionAdorner(ListBox list_box, ScrollViewer scroll_viewer, ScrollContentPresenter scroll_presenter)
: base(scroll_presenter) {
_fill = Fill;
_stroke = Stroke;
// we want our clicks to go through to the underlying grid // we want our clicks to go through to the underlying grid
IsHitTestVisible = false; IsHitTestVisible = false;
// reflect the AdornedElement's clip
IsClipEnabled = true;
_diy_rp = adorned_element; _diy_rp = list_box;
_diy_scroll = scroll_viewer; _diy_scroll = scroll_viewer;
_diy_scp = _diy_rp.descendants_of_type<ScrollContentPresenter>().empty_if_null().FirstOrDefault();
// We actually don't need mouse up/down or key up/down when we can just respond to selection changes // We actually don't need mouse up/down or key up/down when we can just respond to selection changes
_disposables.Add(((System.Windows.Controls.Primitives.Selector)_diy_rp).SubscribeSelectionChanged((s, e) => InvalidateVisual())); _disposables.Add(((System.Windows.Controls.Primitives.Selector)_diy_rp).SubscribeSelectionChanged((s, e) => InvalidateVisual()));
@@ -60,25 +72,24 @@ namespace mbts.ui.controls.adorners {
_disposables.Add(_diy_scroll.SubscribeScrollChanged((s, e) => InvalidateVisual())); _disposables.Add(_diy_scroll.SubscribeScrollChanged((s, e) => InvalidateVisual()));
} }
protected override void OnRender(DrawingContext drawingContext) { protected override void OnRender(DrawingContext drawingContext) {
base.OnRender(drawingContext); base.OnRender(drawingContext);
if (AdornedElement is ListBox lb && lb.SelectedItems != null && lb.SelectedItems.Count > 0) { if (_diy_rp.SelectedItems != null && _diy_rp.SelectedItems.Count > 0) {
foreach(var lbi in lb.SelectedItems) { foreach(var lbi in _diy_rp.SelectedItems) {
if (_diy_rp.ItemContainerGenerator.ContainerFromItem(lbi) is FrameworkElement row && row.IsVisible) { if (_diy_rp.ItemContainerGenerator.ContainerFromItem(lbi) is FrameworkElement row && row.IsVisible) {
var top_left = lb.GetChildTopLeft(row); var top_left = _diy_rp.GetChildTopLeft(row);
var top_is_within_bounds = top_left.Y >= 0; var top_is_within_bounds = top_left.Y >= 0;
// Note that the top of the row can still technically be visible but we wont show // Note that the top of the row can still technically be visible but we wont show
// the adorner rectangle b/c the bottom of the row will be obscured by the scrollbar // the adorner rectangle b/c the bottom of the row will be obscured by the scrollbar
var bottom_is_within_bounds = lb.GetChildBounds(row).BottomRight.Y <= _diy_scroll.ActualHeight; var bottom_is_within_bounds = _diy_rp.GetChildBounds(row).BottomRight.Y <= _diy_scroll.ActualHeight;
if (top_is_within_bounds && bottom_is_within_bounds) { if (top_is_within_bounds && bottom_is_within_bounds) {
// we use the scroll content presenter in the X point calculation instead of the row // we use the scroll content presenter in the X point calculation instead of the row
// because of the OB which has a right side panel that takes up some space over // because of the OB which has a right side panel that takes up some space over
// row width // row width
drawingContext.DrawRectangle(_fill, drawingContext.DrawRectangle(_fill,
_stroke, _stroke,
new Rect(top_left, new Point(top_left.X + _diy_scp.ActualWidth, top_left.Y + row.ActualHeight))); new Rect(top_left, new Point(top_left.X + AdornedElement.RenderSize.Width, top_left.Y + row.ActualHeight)));
} }
} }
} }
@@ -0,0 +1,493 @@
<ResourceDictionary
x:Class="mbts.ui.controls.AutoHideScrollbarResources"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
<sys:Double x:Key="ScrollBarCollapsedWidth">5</sys:Double>
<sys:Double x:Key="ScrollBarCollapsedHeight">5</sys:Double>
<!--Thumb Colors-->
<Color x:Key="ThumbStaticColor">#FFCDCDCD</Color>
<Color x:Key="ThumbMouseOverColor">#FFA6A6A6</Color>
<Color x:Key="ThumbPressedColor">#FF606060</Color>
<!--Line Button Colors-->
<Color x:Key="LineButtonStaticBackgroundColor">#FFF0F0F0</Color>
<Color x:Key="LineButtonMouseOverBackgroundColor">#FFDADADA</Color>
<Color x:Key="LineButtonPressedBackgroundColor">#FF606060</Color>
<Color x:Key="LineButtonStaticForegroundColor">#FF606060</Color>
<Color x:Key="LineButtonMouseOverForegroundColor">#FF000000</Color>
<Color x:Key="LineButtonPressedForegroundColor">#FFFFFFFF</Color>
<Color x:Key="LineButtonDisabledForegroundColor">#FFBFBFBF</Color>
<!--Track-->
<Color x:Key="TrackStaticBackgroundColor">#FFF0F0F0</Color>
<sys:String x:Key="ArrowUpGeometry">
M0,4C0,4 0,6 0,6 0,6 3.5,2.5 3.5,2.5 3.5,2.5 7,6 7,6 7,6 7,4 7,4 7,4 3.5,0.5 3.5,0.5 3.5,0.5 0,4 0,4z
</sys:String>
<sys:String x:Key="ArrowDownGeometry">
M0,2.5C0,2.5 0,0.5 0,0.5 0,0.5 3.5,4 3.5,4 3.5,4 7,0.5 7,0.5 7,0.5 7,2.5 7,2.5 7,2.5 3.5,6 3.5,6 3.5,6 0,2.5 0,2.5z
</sys:String>
<Style x:Key="ScrollBarTrackThumb" TargetType="Thumb">
<Setter Property="Focusable" Value="False"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Thumb">
<Rectangle
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
Fill="{TemplateBinding Background}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="PageButton" TargetType="RepeatButton">
<!--<Setter Property="Background" Value="#FFF0F0F0"/>-->
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RepeatButton">
<Rectangle
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
Fill="{TemplateBinding Background}"
/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="LineButton" TargetType="RepeatButton">
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{StaticResource LineButtonStaticForegroundColor}"/>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RepeatButton">
<Border
Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}"
>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal"/>
<VisualState Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{StaticResource LineButtonMouseOverBackgroundColor}"/>
</Storyboard>
</VisualState>
<VisualState Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{StaticResource LineButtonPressedBackgroundColor}"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border.Background>
<SolidColorBrush Color="{StaticResource LineButtonStaticBackgroundColor}"/>
</Border.Background>
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{StaticResource LineButtonMouseOverForegroundColor}"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{StaticResource LineButtonPressedForegroundColor}"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
<ControlTemplate x:Key="HorizontalScrollBarTemplate" TargetType="ScrollBar">
<Grid
Background="Transparent"
HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
>
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:MouseStateDefinition MouseSource="{Binding Group.Target, RelativeSource={RelativeSource Self}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Track" Storyboard.TargetProperty="Height" BeginTime="00:00:01" Duration="00:00:00.25" To="{StaticResource ScrollBarCollapsedHeight}"/>
<DoubleAnimation Storyboard.TargetName="PART_TrackBackground" Storyboard.TargetProperty="Opacity" BeginTime="00:00:01.75" Duration="00:00:00.20" To="0"/>
<!--Line Up-->
<DoubleAnimation Storyboard.TargetName="PART_LineLeftButton" Storyboard.TargetProperty="Height" BeginTime="00:00:01" Duration="00:00:00.25" To="{StaticResource ScrollBarCollapsedHeight}"/>
<DoubleAnimation Storyboard.TargetName="PART_LineLeftButton" Storyboard.TargetProperty="Opacity" BeginTime="00:00:01.75" Duration="00:00:00.20" To="0"/>
<!--Line Down-->
<DoubleAnimation Storyboard.TargetName="PART_LineRightButton" Storyboard.TargetProperty="Height" BeginTime="00:00:01" Duration="00:00:00.25" To="{StaticResource ScrollBarCollapsedHeight}"/>
<DoubleAnimation Storyboard.TargetName="PART_LineRightButton" Storyboard.TargetProperty="Opacity" BeginTime="00:00:01.75" Duration="00:00:00.20" To="0"/>
</Storyboard>
</VisualState>
<VisualState Name="MouseOver">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Track" Storyboard.TargetProperty="Height" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.HorizontalScrollBarHeight}"/>
<DoubleAnimation Storyboard.TargetName="PART_TrackBackground" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<!--Line Up-->
<DoubleAnimation Storyboard.TargetName="PART_LineLeftButton" Storyboard.TargetProperty="Opacity" BeginTime="00:00:00" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineLeftButton" Storyboard.TargetProperty="Height" BeginTime="00:00:00" Duration="00:00:00.15" To="{x:Static SystemParameters.HorizontalScrollBarHeight}"/>
<!--Line Down-->
<DoubleAnimation Storyboard.TargetName="PART_LineRightButton" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineRightButton" Storyboard.TargetProperty="Height" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.HorizontalScrollBarHeight}"/>
</Storyboard>
</VisualState>
<VisualState Name="Pressed">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Track" Storyboard.TargetProperty="Height" BeginTime="0" Duration="0" To="{x:Static SystemParameters.HorizontalScrollBarHeight}"/>
<DoubleAnimation Storyboard.TargetName="PART_TrackBackground" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<!--Line Up-->
<DoubleAnimation Storyboard.TargetName="PART_LineLeftButton" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineLeftButton" Storyboard.TargetProperty="Height" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.HorizontalScrollBarHeight}"/>
<!--Line Down-->
<DoubleAnimation Storyboard.TargetName="PART_LineRightButton" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineRightButton" Storyboard.TargetProperty="Height" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.HorizontalScrollBarHeight}"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MaxWidth="{x:Static SystemParameters.HorizontalScrollBarButtonWidth}"/>
<ColumnDefinition Width="0.00001*"/>
<ColumnDefinition Width="*" MaxWidth="{x:Static SystemParameters.HorizontalScrollBarButtonWidth}"/>
</Grid.ColumnDefinitions>
<RepeatButton
x:Name="PART_LineLeftButton"
Command="{x:Static ScrollBar.LineLeftCommand}"
Focusable="False"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Opacity="0"
Height="{StaticResource ScrollBarCollapsedHeight}"
Style="{StaticResource LineButton}"
>
<Path
x:Name="ArrowUp"
Data="{Binding Source={StaticResource ArrowUpGeometry}}"
Fill="{Binding Parent.Foreground, RelativeSource={RelativeSource Self}}"
/>
</RepeatButton>
<Track
x:Name="PART_Track"
Grid.Column="1"
IsDirectionReversed="True"
Focusable="False"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Height="{StaticResource ScrollBarCollapsedHeight}"
>
<Track.Thumb>
<Thumb x:Name="Thumb" Style="{StaticResource ScrollBarTrackThumb}">
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:MouseStateDefinition MouseSource="{Binding Group.Target, RelativeSource={RelativeSource Self}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal"/>
<VisualState Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{StaticResource ThumbMouseOverColor}"/>
</Storyboard>
</VisualState>
<VisualState Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{StaticResource ThumbPressedColor}"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Thumb.Background>
<SolidColorBrush Color="{StaticResource ThumbStaticColor}"/>
</Thumb.Background>
</Thumb>
</Track.Thumb>
<Track.IncreaseRepeatButton>
<RepeatButton Command="ScrollBar.PageRightCommand" Style="{StaticResource PageButton}"/>
</Track.IncreaseRepeatButton>
<Track.DecreaseRepeatButton>
<RepeatButton Command="ScrollBar.PageLeftCommand" Style="{StaticResource PageButton}"/>
</Track.DecreaseRepeatButton>
</Track>
<Rectangle
x:Name="PART_TrackBackground"
Grid.Column="1"
Panel.ZIndex="-1"
Focusable="False"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
IsHitTestVisible="False"
Opacity="0"
Height="{Binding ActualHeight, ElementName=PART_Track}"
>
<Shape.Fill>
<SolidColorBrush Color="{StaticResource TrackStaticBackgroundColor}"/>
</Shape.Fill>
</Rectangle>
<RepeatButton
x:Name="PART_LineRightButton"
Grid.Column="2"
Command="{x:Static ScrollBar.LineRightCommand}"
Focusable="False"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Opacity="0"
Height="{StaticResource ScrollBarCollapsedHeight}"
Style="{StaticResource LineButton}"
>
<Path
x:Name="ArrowDown"
Data="{Binding Source={StaticResource ArrowDownGeometry}}"
Fill="{Binding Parent.Foreground, RelativeSource={RelativeSource Self}}"
/>
</RepeatButton>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Thumb" Property="Visibility" Value="Collapsed"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<ControlTemplate x:Key="VerticalScrollBarTemplate" TargetType="ScrollBar">
<Grid
Background="Transparent"
HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
>
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:MouseStateDefinition MouseSource="{Binding Group.Target, RelativeSource={RelativeSource Self}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Track" Storyboard.TargetProperty="Width" BeginTime="00:00:01" Duration="00:00:00.25" To="{StaticResource ScrollBarCollapsedWidth}"/>
<DoubleAnimation Storyboard.TargetName="PART_TrackBackground" Storyboard.TargetProperty="Opacity" BeginTime="00:00:01.75" Duration="00:00:00.20" To="0"/>
<!--Line Up-->
<DoubleAnimation Storyboard.TargetName="PART_LineUpButton" Storyboard.TargetProperty="Width" BeginTime="00:00:01" Duration="00:00:00.25" To="{StaticResource ScrollBarCollapsedWidth}"/>
<DoubleAnimation Storyboard.TargetName="PART_LineUpButton" Storyboard.TargetProperty="Opacity" BeginTime="00:00:01.75" Duration="00:00:00.20" To="0"/>
<!--Line Down-->
<DoubleAnimation Storyboard.TargetName="PART_LineDownButton" Storyboard.TargetProperty="Width" BeginTime="00:00:01" Duration="00:00:00.25" To="{StaticResource ScrollBarCollapsedWidth}"/>
<DoubleAnimation Storyboard.TargetName="PART_LineDownButton" Storyboard.TargetProperty="Opacity" BeginTime="00:00:01.75" Duration="00:00:00.20" To="0"/>
</Storyboard>
</VisualState>
<VisualState Name="MouseOver">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Track" Storyboard.TargetProperty="Width" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.VerticalScrollBarWidth}"/>
<DoubleAnimation Storyboard.TargetName="PART_TrackBackground" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<!--Line Up-->
<DoubleAnimation Storyboard.TargetName="PART_LineUpButton" Storyboard.TargetProperty="Opacity" BeginTime="00:00:00" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineUpButton" Storyboard.TargetProperty="Width" BeginTime="00:00:00" Duration="00:00:00.15" To="{x:Static SystemParameters.VerticalScrollBarWidth}"/>
<!--Line Down-->
<DoubleAnimation Storyboard.TargetName="PART_LineDownButton" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineDownButton" Storyboard.TargetProperty="Width" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.VerticalScrollBarWidth}"/>
</Storyboard>
</VisualState>
<VisualState Name="Pressed">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Track" Storyboard.TargetProperty="Width" BeginTime="0" Duration="0" To="{x:Static SystemParameters.VerticalScrollBarWidth}"/>
<DoubleAnimation Storyboard.TargetName="PART_TrackBackground" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<!--Line Up-->
<DoubleAnimation Storyboard.TargetName="PART_LineUpButton" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineUpButton" Storyboard.TargetProperty="Width" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.VerticalScrollBarWidth}"/>
<!--Line Down-->
<DoubleAnimation Storyboard.TargetName="PART_LineDownButton" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="PART_LineDownButton" Storyboard.TargetProperty="Width" BeginTime="0" Duration="00:00:00.15" To="{x:Static SystemParameters.VerticalScrollBarWidth}"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.RowDefinitions>
<RowDefinition Height="*" MaxHeight="{x:Static SystemParameters.VerticalScrollBarButtonHeight}"/>
<RowDefinition Height="0.00001*"/>
<RowDefinition Height="*" MaxHeight="{x:Static SystemParameters.VerticalScrollBarButtonHeight}"/>
</Grid.RowDefinitions>
<RepeatButton
x:Name="PART_LineUpButton"
Command="{x:Static ScrollBar.LineUpCommand}"
Focusable="False"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Opacity="0"
Width="{StaticResource ScrollBarCollapsedWidth}"
Style="{StaticResource LineButton}"
>
<Path
x:Name="ArrowUp"
Data="{Binding Source={StaticResource ArrowUpGeometry}}"
Fill="{Binding Parent.Foreground, RelativeSource={RelativeSource Self}}"
/>
</RepeatButton>
<Track
x:Name="PART_Track"
Grid.Row="1"
IsDirectionReversed="True"
Focusable="False"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Width="{StaticResource ScrollBarCollapsedWidth}"
>
<Track.Thumb>
<Thumb x:Name="Thumb" Style="{StaticResource ScrollBarTrackThumb}">
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:MouseStateDefinition MouseSource="{Binding Group.Target, RelativeSource={RelativeSource Self}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal"/>
<VisualState Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{StaticResource ThumbMouseOverColor}"/>
</Storyboard>
</VisualState>
<VisualState Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{StaticResource ThumbPressedColor}"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Thumb.Background>
<SolidColorBrush Color="{StaticResource ThumbStaticColor}"/>
</Thumb.Background>
</Thumb>
</Track.Thumb>
<Track.IncreaseRepeatButton>
<RepeatButton Command="ScrollBar.PageDownCommand" Style="{StaticResource PageButton}"/>
</Track.IncreaseRepeatButton>
<Track.DecreaseRepeatButton>
<RepeatButton Command="ScrollBar.PageUpCommand" Style="{StaticResource PageButton}"/>
</Track.DecreaseRepeatButton>
</Track>
<Rectangle
x:Name="PART_TrackBackground"
Grid.Row="1"
Panel.ZIndex="-1"
Focusable="False"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
IsHitTestVisible="False"
Opacity="0"
Width="{Binding ActualWidth, ElementName=PART_Track}"
>
<Shape.Fill>
<SolidColorBrush Color="{StaticResource TrackStaticBackgroundColor}"/>
</Shape.Fill>
</Rectangle>
<RepeatButton
x:Name="PART_LineDownButton"
Grid.Row="2"
Command="{x:Static ScrollBar.LineDownCommand}"
Focusable="False"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Opacity="0"
Width="{StaticResource ScrollBarCollapsedWidth}"
Style="{StaticResource LineButton}"
>
<Path
x:Name="ArrowDown"
Data="{Binding Source={StaticResource ArrowDownGeometry}}"
Fill="{Binding Parent.Foreground, RelativeSource={RelativeSource Self}}"
/>
</RepeatButton>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Thumb" Property="Visibility" Value="Collapsed"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<Style x:Key="VerticalScrollBar" TargetType="c:AutoHideScrollBar">
<Setter Property="Template" Value="{StaticResource VerticalScrollBarTemplate}"/>
</Style>
<Style TargetType="ScrollViewer" BasedOn="{StaticResource {x:Type ScrollViewer}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ScrollViewer">
<Grid>
<ScrollContentPresenter
x:Name="PART_ScrollContentPresenter"
CanContentScroll="{TemplateBinding CanContentScroll}"
>
<ScrollContentPresenter.Clip>
<MultiBinding Converter="{x:Static c:AutoHideScrollBar.ScrollContentClipConverter}">
<Binding ElementName="PART_VerticalScrollBar" Path="VisibleWidth" Mode="OneWay"/>
<Binding ElementName="PART_HorizontalScrollBar" Path="VisibleHeight" Mode="OneWay"/>
<Binding RelativeSource="{RelativeSource Self}" Path="ActualWidth" Mode="OneWay"/>
<Binding RelativeSource="{RelativeSource Self}" Path="ActualHeight" Mode="OneWay"/>
</MultiBinding>
</ScrollContentPresenter.Clip>
</ScrollContentPresenter>
<c:AutoHideScrollBar
x:Name="PART_VerticalScrollBar"
Cursor="{TemplateBinding Cursor}"
HorizontalAlignment="Right"
HorizontalContentAlignment="Right"
Maximum="{TemplateBinding ScrollableHeight}"
Value="{TemplateBinding VerticalOffset}"
ViewportSize="{TemplateBinding ViewportHeight}"
Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
Template="{StaticResource VerticalScrollBarTemplate}"
>
</c:AutoHideScrollBar>
<c:AutoHideScrollBar
x:Name="PART_HorizontalScrollBar"
Cursor="{TemplateBinding Cursor}"
Maximum="{TemplateBinding ScrollableWidth}"
Orientation="Horizontal"
Value="{TemplateBinding HorizontalOffset}"
VerticalAlignment="Bottom"
VerticalContentAlignment="Bottom"
ViewportSize="{TemplateBinding ViewportWidth}"
Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
Template="{StaticResource HorizontalScrollBarTemplate}"
/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
@@ -0,0 +1,80 @@
using mbts.ui.converters;
using mbts.ui.extensions;
using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
namespace mbts.ui.controls {
partial class AutoHideScrollbarResources : ResourceDictionary {
public AutoHideScrollbarResources() =>
InitializeComponent();
}
class AutoHideScrollBar : ScrollBar {
IDisposable _hooks;
public static IMultiValueConverter ScrollContentClipConverter =
ValueConverter.create<double, double, double, double, RectangleGeometry>(
(scroll_bar_width, scroll_bar_height, content_width, content_height) =>
new RectangleGeometry(
new Rect(new Size(
Math.Max(0, content_width - DoubleHelper.CoerceNaN(scroll_bar_width, 0)),
Math.Max(0, content_height - DoubleHelper.CoerceNaN(scroll_bar_height, 0))))));
#region VisibleWidth
static readonly DependencyPropertyKey VisibleWidthPropertyKey =
DependencyProperty.RegisterAttachedReadOnly(
nameof(VisibleWidth),
typeof(double),
typeof(AutoHideScrollBar),
new PropertyMetadata(double.NaN, null, CoerceVisibleWidth));
static object CoerceVisibleWidth(DependencyObject d, object baseValue) =>
(d as AutoHideScrollBar)?.Track?.ActualWidth ?? baseValue;
public static readonly DependencyProperty VisibleWidthProperty =
VisibleWidthPropertyKey.DependencyProperty;
public double VisibleWidth {
get => (double)GetValue(VisibleWidthProperty);
private set => SetValue(VisibleWidthPropertyKey, value);
}
#endregion
#region VisibleHeight
static readonly DependencyPropertyKey VisibleHeightPropertyKey =
DependencyProperty.RegisterAttachedReadOnly(
nameof(VisibleHeight),
typeof(double),
typeof(AutoHideScrollBar),
new PropertyMetadata(double.NaN, null, CoerceVisibleHeight));
static object CoerceVisibleHeight(DependencyObject d, object baseValue) =>
(d as AutoHideScrollBar)?.Track?.ActualHeight ?? baseValue;
public static readonly DependencyProperty VisibleHeightProperty =
VisibleHeightPropertyKey.DependencyProperty;
public double VisibleHeight {
get => (double)GetValue(VisibleHeightProperty);
private set => SetValue(VisibleHeightPropertyKey, value);
}
#endregion
public override void OnApplyTemplate() {
Disposable.dispose(ref _hooks);
/// call base method first to ensure <see cref="ScrollBar.Track"/> is initialized.
base.OnApplyTemplate();
_hooks = Track.SubscribeSizeChanged((s, e) => {
if (e.WidthChanged)
CoerceValue(VisibleWidthProperty);
if (e.HeightChanged)
CoerceValue(VisibleHeightProperty);
});
CoerceValue(VisibleWidthProperty);
CoerceValue(VisibleHeightProperty);
}
}
}
@@ -1,4 +1,5 @@
using mbts.ui.converters; using mbts.ui.dpi;
using mbts.ui.converters;
using mbts.ui.shell; using mbts.ui.shell;
using mbts.ui.utility.text; using mbts.ui.utility.text;
using System; using System;
@@ -10,6 +11,7 @@ using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Media; using System.Windows.Media;
using bts;
namespace mbts.ui.controls { namespace mbts.ui.controls {
partial class DIYGrid { partial class DIYGrid {
@@ -83,79 +85,39 @@ namespace mbts.ui.controls {
} }
} }
public static Rect? get_clip(Size content_size, double row_height, double left, double unclipped_left, double width) =>
content_size == null ? get_clip(0, 0, row_height, left, unclipped_left, width) :
get_clip(content_size.Width, content_size.Height, row_height, left, unclipped_left, width);
public static Rect? get_clip(double content_width, double content_height, double row_height, double left, double unclipped_left, double width) {
if (content_width > width || unclipped_left < left)
return new Rect(left, 0, width - left + unclipped_left, row_height);
return null;
}
public static IDisposable draw_with_clip(DrawingContext dc, double raw_content_width, double raw_content_height, Thickness padding, double row_height, ColumnGeometry position) =>
draw_with_clip(dc,
raw_content_width + padding.Left + padding.Right,
raw_content_height + padding.Top + padding.Bottom,
row_height, position.left, position.unclipped_left, position.width);
public static IDisposable draw_with_clip(DrawingContext dc, double content_width, double content_height, double row_height, double left, double unclipped_left, double width) {
var clip = get_clip(content_width, content_height, row_height, left, unclipped_left, width);
if (clip.HasValue) {
dc.PushClip(new RectangleGeometry(clip.Value));
return Disposable.Create(dc.Pop);
} else return Disposable.Create(() => { });
}
public static void draw_text( public static void draw_text(
DrawingContext dc, GlyphContext glyph_context, double font_size, string text, ColumnGeometry position, double row_height, DrawingContext dc,
Brush foreground, Brush background, HorizontalAlignment x_align, VerticalAlignment y_align, Thickness padding) { GlyphContext glyph_context,
double font_size,
string text,
ColumnGeometry position,
double row_height,
Brush foreground,
Brush background,
HorizontalAlignment x_align,
VerticalAlignment y_align,
Thickness padding,
bool round_to_layout = true) {
// //
if (!string.IsNullOrEmpty(text)) { var gr = glyph_context.get_glyph_run(text, font_size, position.unclipped_left, 0, position.right, row_height, x_align, y_align, padding, round_to_layout);
var gr = glyph_context.get_glyph_run(text, font_size, position.unclipped_left, 0, position.right, row_height, x_align, y_align, padding); var gwidth = gr == null ? 0 : gr.ComputeAlignmentBox().Width;
draw_text(dc, gr, gr.AdvanceWidths.Sum(), font_size, position, padding, row_height, foreground, background); draw_text(dc, gr, gwidth, font_size, position, padding, row_height, foreground, background);
}
} }
public static void draw_text(DrawingContext dc, GlyphRun glyph_run, double glyph_width, double font_size, ColumnGeometry position, Thickness padding, double row_height, Brush foreground, Brush background) { public static void draw_text(DrawingContext dc, GlyphRun glyph_run, double glyph_width, double font_size, ColumnGeometry position, Thickness padding, double row_height, Brush foreground, Brush background) {
using (draw_with_clip(dc, glyph_width, font_size, padding, row_height, position)) { if (glyph_run == null && background == null)
if (background != null) return;
dc.DrawRectangle(background, null, new Rect(position.left, 0, position.width, row_height)); var rect = position.to_rect(row_height);
dc.DrawGlyphRun(foreground, glyph_run); if (background != null) {
var guidelines = rect.AntiAliasGuidelines(0);
dc.PushGuidelineSet(guidelines);
dc.DrawRectangle(background, null, rect);
dc.Pop();
} }
} if (glyph_run != null) {
dc.PushClip(new RectangleGeometry(rect));
public static void draw_text( dc.DrawGlyphRun(foreground, glyph_run);
DrawingContext dc, GlyphContext glyph_context, double font_size, string text, ColumnGeometry position, double row_height, dc.Pop();
Brush foreground, Brush background, HorizontalAlignment x_align, VerticalAlignment y_align, Thickness padding, IEnumerable<CellAnimation> trigger_actions) {
//
using (position.clip_draw(dc, row_height)) {
double adjusted_left = position.unclipped_left;
double available_width = position.width;
if (background != null)
dc.DrawRectangle(background, null, new Rect(position.left, 0, position.width, row_height));
// store any trigger-glyphs in a list, to be drawn after iterating through all triggers (must draw background first, so glyphs will not be covered up).
List<(Brush brush, GlyphRun glyph)> glyphs = new List<(Brush brush, GlyphRun glyph)>(1);
if (trigger_actions != null) {
foreach (CellAnimation ta in trigger_actions) {
switch (ta.animation_type_case) {
case CellAnimation.AnimationTypeOneofCase.BackgroundAnimation:
dc.DrawRectangle(ta.background_animation.brush, ta.background_animation.pen, new Rect(position.left, 0, position.width, row_height));
break;
case CellAnimation.AnimationTypeOneofCase.SymbolAnimation:
var (symbol_text, is_sideways) = _get_symbol_animation_args(ta.symbol_animation);
GlyphRun symbol_glyph = glyph_context.get_glyph_run(symbol_text, font_size, position.width, row_height, HorizontalAlignment.Left, adjusted_left, y_align, 0, is_sideways: is_sideways);
glyphs.Add((ta.symbol_animation.brush, symbol_glyph));
adjusted_left += symbol_glyph.AdvanceWidths.Sum();
break;
}
}
}
foreach (var (brush, glyph) in glyphs) {
dc.DrawGlyphRun(brush, glyph);
}
GlyphRun main_content = glyph_context.get_glyph_run(text, font_size, adjusted_left, 0, position.right, row_height, x_align, y_align, padding);
draw_text(dc, main_content, main_content.AdvanceWidths.Sum(), font_size, position, padding, row_height, foreground, background);
} }
} }
@@ -165,14 +127,6 @@ namespace mbts.ui.controls {
public static void change_position(FrameworkElement cell_view, double row_height, ColumnGeometry? position) { public static void change_position(FrameworkElement cell_view, double row_height, ColumnGeometry? position) {
if (position.HasValue) { if (position.HasValue) {
WPFHelper.set_if_changed(cell_view, VisibilityProperty, Visibility.Visible); WPFHelper.set_if_changed(cell_view, VisibilityProperty, Visibility.Visible);
var clip = get_clip(cell_view.DesiredSize, row_height, 0, position.Value.unclipped_left - position.Value.left, position.Value.width);
var el_clip = cell_view.Clip as RectangleGeometry;
if (clip.HasValue) {
if (el_clip == null || !el_clip.Rect.Equals(clip.Value))
cell_view.Clip = new RectangleGeometry(clip.Value);
} else if (cell_view.Clip != null) {
cell_view.Clip = null;
}
} else { } else {
WPFHelper.set_if_changed(cell_view, VisibilityProperty, Visibility.Collapsed); WPFHelper.set_if_changed(cell_view, VisibilityProperty, Visibility.Collapsed);
} }
@@ -1,16 +1,25 @@
using mbts.ui.utilities; using mbts.spark;
using mbts.ui.dpi;
using mbts.ui.utilities;
using mbts.ui.utility.text; using mbts.ui.utility.text;
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Reactive.Linq;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Documents; using System.Windows.Documents;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Threading;
using FontFamily = System.Windows.Media.FontFamily; using FontFamily = System.Windows.Media.FontFamily;
namespace mbts.ui.controls { namespace mbts.ui.controls {
enum HyperlinkCellClickMode {
Text,
Anywhere
}
class HyperlinkCell : FrameworkElement, ICommandSource { class HyperlinkCell : FrameworkElement, ICommandSource {
// these fields each represent properties that are accessed frequently, // these fields each represent properties that are accessed frequently,
// they are stored locally to reduce repetative DependencyProperty lookups // they are stored locally to reduce repetative DependencyProperty lookups
@@ -18,10 +27,35 @@ namespace mbts.ui.controls {
Brush _background, _foreground_backing, _border_brush_backing; Brush _background, _foreground_backing, _border_brush_backing;
double _glyph_width => _gcr.glyph_run.AdvanceWidths.Sum(); double _glyph_width => _gcr.glyph_run.AdvanceWidths.Sum();
GlyphRun _glyph_run => _gcr.glyph_run; GlyphRun _glyph_run => _gcr.glyph_run;
bool _is_mouse_over_text, _can_execute; bool
_is_mouse_over_text,
_is_mouse_over_click_area_backing,
_can_execute,
_snaps_to_device_pixels;
Pen _underline_pen_backing, _border_stroke_pen_backing; Pen _underline_pen_backing, _border_stroke_pen_backing;
GlyphContentRect _gcr = new GlyphContentRect(); GlyphContentRect _gcr = new GlyphContentRect {
// add 2 pixels to account for underline (1 for space, 1 for the line itself)
content_height_offset = HighDpiExtensions.pixel_unit * 2
};
IDisposable _mouse_over_click_area_op;
bool _is_mouse_over_click_area {
get => _is_mouse_over_click_area_backing;
set {
if (_is_mouse_over_click_area_backing != value) {
Disposable.dispose(ref _mouse_over_click_area_op);
_is_mouse_over_click_area_backing = value;
if (value) {
_mouse_over_click_area_op = WorkLoop.Start(
$"Evaluate {nameof(HyperlinkCell)} {nameof(IsMouseOverClickArea)}",
TimeSpan.FromMilliseconds(100),
DispatcherPriority.Input,
_on_mouse_changed,
WorkLoop.default_excessive_cycle_ratio);
}
}
}
}
Brush _foreground { Brush _foreground {
get => _foreground_backing; get => _foreground_backing;
set { set {
@@ -37,13 +71,23 @@ namespace mbts.ui.controls {
} }
} }
Thickness _border_thickness { Thickness _border_thickness {
get => _gcr.border_thickness; get => _snaps_to_device_pixels ? _gcr.border_thickness.RoundToLayout() : _gcr.border_thickness;
set { set {
_gcr.border_thickness = new Thickness(value.Left); _gcr.border_thickness = new Thickness(value.Left);
_border_stroke_pen_backing = null; _border_stroke_pen_backing = null;
} }
} }
Pen _underline_pen => _underline_pen_backing ?? (_foreground == null ? null : (_underline_pen_backing = new Pen(_foreground, 1))); Pen _underline_pen {
get {
if (_underline_pen_backing == null) {
var fg = _foreground;
if (fg != null) {
_underline_pen_backing = new Pen(fg, _snaps_to_device_pixels ? HighDpiExtensions.pixel_unit : 1);
}
}
return _underline_pen_backing;
}
}
Pen _border_stroke_pen => Pen _border_stroke_pen =>
// border_thickness.Left is used as the uniform border thickness. This can be changed if need be. // border_thickness.Left is used as the uniform border thickness. This can be changed if need be.
_border_stroke_pen_backing == null && _border_brush != null && _border_thickness.Left > 0 ? _border_stroke_pen_backing == null && _border_brush != null && _border_thickness.Left > 0 ?
@@ -51,6 +95,8 @@ namespace mbts.ui.controls {
_border_stroke_pen_backing; _border_stroke_pen_backing;
static HyperlinkCell() { static HyperlinkCell() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(HyperlinkCell), new FrameworkPropertyMetadata(typeof(HyperlinkCell)));
IsMouseOverClickAreaProperty = IsMouseOverClickAreaPropertyKey.DependencyProperty;
WPFHelper.override_metadata<HorizontalAlignment, HyperlinkCell>( WPFHelper.override_metadata<HorizontalAlignment, HyperlinkCell>(
HorizontalAlignmentProperty, HorizontalAlignmentProperty,
FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsArrange |
@@ -64,6 +110,11 @@ namespace mbts.ui.controls {
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._gcr.width = v, (o, v) => o._gcr.width = v,
double.NaN); double.NaN);
WPFHelper.override_metadata<bool, HyperlinkCell>(
SnapsToDevicePixelsProperty,
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._snaps_to_device_pixels = v,
true);
} }
public HyperlinkCell() { public HyperlinkCell() {
@@ -73,7 +124,7 @@ namespace mbts.ui.controls {
_gcr.min_height = MinHeight; _gcr.min_height = MinHeight;
_gcr.height = Height; _gcr.height = Height;
_gcr.max_height = Height; _gcr.max_height = Height;
_gcr.padding = _underline_padding(Padding); _gcr.padding = Padding;
_gcr.border_thickness = BorderThickness; _gcr.border_thickness = BorderThickness;
_gcr.horizontal_alignment = HorizontalAlignment; _gcr.horizontal_alignment = HorizontalAlignment;
_gcr.horizontal_content_alignment = HorizontalContentAlignment; _gcr.horizontal_content_alignment = HorizontalContentAlignment;
@@ -86,8 +137,39 @@ namespace mbts.ui.controls {
if (Text is string str && !string.IsNullOrEmpty(str)) if (Text is string str && !string.IsNullOrEmpty(str))
_gcr.text_lines = new[] { str }; _gcr.text_lines = new[] { str };
_gcr.glyph_context = GlyphContext.create(FontFamily, FontWeight); _gcr.glyph_context = GlyphContext.create(FontFamily, FontWeight);
_snaps_to_device_pixels = SnapsToDevicePixels;
} }
#region IsMouseOverClickArea
static readonly DependencyPropertyKey IsMouseOverClickAreaPropertyKey =
DependencyProperty.RegisterReadOnly(
"IsMouseOverClickArea",
typeof(bool),
typeof(HyperlinkCell),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.AffectsRender,
OnIsMouseOverClickAreaChanged,
CoerceIsMouseOverClickArea));
public static readonly DependencyProperty IsMouseOverClickAreaProperty;
static void OnIsMouseOverClickAreaChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (d is HyperlinkCell hlc)
hlc._is_mouse_over_click_area = e.NewValue is bool b && b;
}
static object CoerceIsMouseOverClickArea(DependencyObject d, object baseValue) =>
d is HyperlinkCell hlc ?
hlc._is_mouse_over_text || (hlc.IsMouseOver && hlc.HyperlinkClickMode == HyperlinkCellClickMode.Anywhere) :
baseValue;
public bool IsMouseOverClickArea {
get => (bool)GetValue(IsMouseOverClickAreaProperty);
private set => SetValue(IsMouseOverClickAreaPropertyKey, value);
}
#endregion
#region BorderThickness #region BorderThickness
public static readonly DependencyProperty BorderThicknessProperty = public static readonly DependencyProperty BorderThicknessProperty =
Control.BorderThicknessProperty.AddOwner(typeof(HyperlinkCell), Control.BorderThicknessProperty.AddOwner(typeof(HyperlinkCell),
@@ -122,6 +204,7 @@ namespace mbts.ui.controls {
Control.HorizontalContentAlignmentProperty.AddOwner(typeof(HyperlinkCell), Control.HorizontalContentAlignmentProperty.AddOwner(typeof(HyperlinkCell),
new FrameworkPropertyMetadata( new FrameworkPropertyMetadata(
HorizontalAlignment.Center, HorizontalAlignment.Center,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsArrange, FrameworkPropertyMetadataOptions.AffectsArrange,
(d, e) => ((HyperlinkCell)d)._gcr.horizontal_content_alignment = (HorizontalAlignment)e.NewValue)); (d, e) => ((HyperlinkCell)d)._gcr.horizontal_content_alignment = (HorizontalAlignment)e.NewValue));
@@ -135,7 +218,8 @@ namespace mbts.ui.controls {
public static readonly DependencyProperty VerticalContentAlignmentProperty = Control.VerticalContentAlignmentProperty.AddOwner(typeof(HyperlinkCell), public static readonly DependencyProperty VerticalContentAlignmentProperty = Control.VerticalContentAlignmentProperty.AddOwner(typeof(HyperlinkCell),
new FrameworkPropertyMetadata( new FrameworkPropertyMetadata(
VerticalAlignment.Center, VerticalAlignment.Center,
FrameworkPropertyMetadataOptions.AffectsArrange, FrameworkPropertyMetadataOptions.AffectsArrange |
FrameworkPropertyMetadataOptions.AffectsRender,
(d, e) => ((HyperlinkCell)d)._gcr.vertical_content_alignment = (VerticalAlignment)e.NewValue)); (d, e) => ((HyperlinkCell)d)._gcr.vertical_content_alignment = (VerticalAlignment)e.NewValue));
public VerticalAlignment VerticalContentAlignment { public VerticalAlignment VerticalContentAlignment {
@@ -215,7 +299,8 @@ namespace mbts.ui.controls {
nameof(Padding), nameof(Padding),
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(p, v) => p._gcr.padding = _underline_padding(v), DIYGrid.DefaultCellPadding); (p, v) => p._gcr.padding = v,
DIYGrid.DefaultCellPadding);
public Thickness Padding { get => (Thickness)GetValue(PaddingProperty); set => SetValue(PaddingProperty, value); } public Thickness Padding { get => (Thickness)GetValue(PaddingProperty); set => SetValue(PaddingProperty, value); }
#endregion #endregion
@@ -231,6 +316,19 @@ namespace mbts.ui.controls {
public string Text { get => GetValue(TextProperty) as string; set => SetValue(TextProperty, value); } public string Text { get => GetValue(TextProperty) as string; set => SetValue(TextProperty, value); }
#endregion #endregion
#region HyperlinkClickMode
public static readonly DependencyProperty HyperlinkClickModeProperty =
WPFHelper.create_dp<HyperlinkCellClickMode, HyperlinkCell>(
nameof(HyperlinkClickMode),
(o, v) => o.CoerceValue(IsMouseOverClickAreaProperty),
HyperlinkCellClickMode.Anywhere);
public HyperlinkCellClickMode HyperlinkClickMode {
get => (HyperlinkCellClickMode)GetValue(HyperlinkClickModeProperty);
set => SetValue(HyperlinkClickModeProperty, value);
}
#endregion
#region ICommandSource #region ICommandSource
#region Command #region Command
@@ -297,8 +395,8 @@ namespace mbts.ui.controls {
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {
base.OnMouseLeftButtonDown(e); base.OnMouseLeftButtonDown(e);
_check_mouse_over_text(e); _on_mouse_changed(e);
if (_is_mouse_over_text) { if (_is_mouse_over_click_area) {
// Hyperlink should take focus when left mouse button is clicked on it // Hyperlink should take focus when left mouse button is clicked on it
// This is consistent with all ButtonBase controls and current Win32 behavior // This is consistent with all ButtonBase controls and current Win32 behavior
Focus(); Focus();
@@ -308,6 +406,8 @@ namespace mbts.ui.controls {
if (e.ButtonState == MouseButtonState.Pressed) { if (e.ButtonState == MouseButtonState.Pressed) {
// Capture the mouse, and make sure we got it. // Capture the mouse, and make sure we got it.
CaptureMouse(); CaptureMouse();
} else {
ReleaseMouseCapture();
} }
e.Handled = true; e.Handled = true;
} }
@@ -315,23 +415,25 @@ namespace mbts.ui.controls {
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) {
base.OnMouseLeftButtonUp(e); base.OnMouseLeftButtonUp(e);
_check_mouse_over_text(e); _on_mouse_changed(e);
if (IsMouseCaptured) if (IsMouseCaptured) {
ReleaseMouseCapture(); ReleaseMouseCapture();
if (_can_execute && _is_mouse_over_text) if (_can_execute)
CommandHelper.ExecuteCommandSource(this); CommandHelper.ExecuteCommandSource(this);
e.Handled = true; _on_mouse_changed(e);
e.Handled = true;
}
} }
#endregion #endregion
protected override void OnIsMouseDirectlyOverChanged(DependencyPropertyChangedEventArgs e) { protected override void OnIsMouseDirectlyOverChanged(DependencyPropertyChangedEventArgs e) => _on_mouse_changed();
if (_is_mouse_over_text != IsMouseDirectlyOver) protected override void OnPreviewMouseMove(MouseEventArgs e) {
_toggle_mouse_over_text(); _on_mouse_changed(e);
e.Handled = IsMouseCaptured;
} }
protected override void OnPreviewMouseMove(MouseEventArgs e) => _check_mouse_over_text(e); protected override void OnMouseEnter(MouseEventArgs e) => _on_mouse_changed(e);
protected override void OnMouseEnter(MouseEventArgs e) => _check_mouse_over_text(e); protected override void OnMouseLeave(MouseEventArgs e) => _on_mouse_changed(e);
protected override void OnMouseLeave(MouseEventArgs e) => _check_mouse_over_text(e);
protected override Size ArrangeOverride(Size finalSize) => finalSize; protected override Size ArrangeOverride(Size finalSize) => finalSize;
@@ -347,45 +449,32 @@ namespace mbts.ui.controls {
var rs = RenderSize; var rs = RenderSize;
var rect = new Rect(0, 0, rs.Width, rs.Height); var rect = new Rect(0, 0, rs.Width, rs.Height);
var bg = Background; var bg = Background;
if (bg != null) { drawingContext.DrawRectangle(bg, _border_stroke_pen, rect, _snaps_to_device_pixels);
drawingContext.DrawRectangle(bg, _border_stroke_pen, rect); var gr = _glyph_run;
} if (gr != null) {
if (_glyph_run != null) {
drawingContext.PushClip(new RectangleGeometry(rect)); drawingContext.PushClip(new RectangleGeometry(rect));
drawingContext.DrawGlyphRun(_foreground, _glyph_run); drawingContext.DrawGlyphRun(_foreground, gr);
if (_is_mouse_over_text) { if (IsMouseOverClickArea) {
// draw underline // draw underline
double x = _gcr.glyph_run.BaselineOrigin.X; var ul_pen = _underline_pen;
double y = _gcr.glyph_run.BaselineOrigin.Y + 2; if (ul_pen != null) {
drawingContext.DrawLine(_underline_pen, new Point(x, y), new Point(x + _gcr.glyph_run.AdvanceWidths.Sum(), y)); var line_start = new Point(gr.BaselineOrigin.X, gr.BaselineOrigin.Y + 2 * ul_pen.Thickness);
drawingContext.DrawHorizontalLine(ul_pen, line_start, gr.AdvanceWidths.Sum(), _snaps_to_device_pixels);
}
} }
drawingContext.Pop(); drawingContext.Pop();
} }
} }
static Thickness _underline_padding(Thickness padding) => void _on_mouse_changed() =>
new Thickness(padding.Left, padding.Top, padding.Right, padding.Bottom + 2); _on_mouse_changed(Mouse.GetPosition(this));
void _check_mouse_over_text(MouseEventArgs e) { void _on_mouse_changed(MouseEventArgs e) =>
var pt = e.GetPosition(this); _on_mouse_changed(e.GetPosition(this));
var orig = _gcr.content_area;
var exp = orig.Expanded(1);
if (_is_mouse_over_text != exp.Contains(pt)) {
bts.Log.assert(_is_mouse_over_text != _gcr.content_area.Expanded(1).Contains(e.GetPosition(this)));
_toggle_mouse_over_text();
return;
}
if (_is_mouse_over_text != _gcr.content_area.Expanded(1).Contains(e.GetPosition(this)))
_toggle_mouse_over_text();
}
void _toggle_mouse_over_text() { void _on_mouse_changed(Point pt) {
_is_mouse_over_text = !_is_mouse_over_text; _is_mouse_over_text = _gcr.content_area.Expanded(1).Contains(pt);
if (_is_mouse_over_text) CoerceValue(IsMouseOverClickAreaProperty);
SetCurrentValue(CursorProperty, Cursors.Hand);
else
ClearValue(CursorProperty);
InvalidateVisual();
} }
} }
} }
@@ -1,5 +1,5 @@
using mbts.ui.utility.text; using mbts.ui.dpi;
using System; using mbts.ui.utility.text;
using System.Linq; using System.Linq;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
@@ -15,6 +15,7 @@ namespace mbts.ui.controls {
Brush _background, _foreground, _border_brush_backing; Brush _background, _foreground, _border_brush_backing;
double _glyph_width => _gcr.glyph_run.AdvanceWidths.Sum(); double _glyph_width => _gcr.glyph_run.AdvanceWidths.Sum();
GlyphRun _glyph_run => _gcr.glyph_run; GlyphRun _glyph_run => _gcr.glyph_run;
bool _snaps_to_device_pixels;
Pen _border_stroke_pen_backing; Pen _border_stroke_pen_backing;
GlyphContentRect _gcr = new GlyphContentRect(); GlyphContentRect _gcr = new GlyphContentRect();
@@ -26,7 +27,7 @@ namespace mbts.ui.controls {
} }
} }
Thickness _border_thickness { Thickness _border_thickness {
get => _gcr.border_thickness; get => _snaps_to_device_pixels ? _gcr.border_thickness.RoundToLayout() : _gcr.border_thickness;
set { set {
_gcr.border_thickness = new Thickness(value.Left); _gcr.border_thickness = new Thickness(value.Left);
_border_stroke_pen_backing = null; _border_stroke_pen_backing = null;
@@ -52,6 +53,11 @@ namespace mbts.ui.controls {
FrameworkPropertyMetadataOptions.AffectsRender, FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._gcr.width = v, (o, v) => o._gcr.width = v,
double.NaN); double.NaN);
WPFHelper.override_metadata<bool, TextCell>(
SnapsToDevicePixelsProperty,
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._snaps_to_device_pixels = v,
true);
} }
public TextCell() { public TextCell() {
@@ -60,7 +66,7 @@ namespace mbts.ui.controls {
_gcr.max_width = MaxWidth; _gcr.max_width = MaxWidth;
_gcr.min_height = MinHeight; _gcr.min_height = MinHeight;
_gcr.height = Height; _gcr.height = Height;
_gcr.max_height = Height; _gcr.max_height = MaxHeight;
_gcr.padding = Padding; _gcr.padding = Padding;
_gcr.border_thickness = BorderThickness; _gcr.border_thickness = BorderThickness;
_gcr.horizontal_alignment = HorizontalAlignment; _gcr.horizontal_alignment = HorizontalAlignment;
@@ -74,6 +80,7 @@ namespace mbts.ui.controls {
if (Text is string str && !string.IsNullOrEmpty(str)) if (Text is string str && !string.IsNullOrEmpty(str))
_gcr.text_lines = new[] { str }; _gcr.text_lines = new[] { str };
_gcr.glyph_context = GlyphContext.create(FontFamily, FontWeight); _gcr.glyph_context = GlyphContext.create(FontFamily, FontWeight);
_snaps_to_device_pixels = SnapsToDevicePixels;
} }
#region BorderThickness #region BorderThickness
@@ -110,15 +117,9 @@ namespace mbts.ui.controls {
Control.HorizontalContentAlignmentProperty.AddOwner(typeof(TextCell), Control.HorizontalContentAlignmentProperty.AddOwner(typeof(TextCell),
new FrameworkPropertyMetadata( new FrameworkPropertyMetadata(
HorizontalAlignment.Center, HorizontalAlignment.Center,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsArrange, FrameworkPropertyMetadataOptions.AffectsArrange,
(d, e) => { (d, e) => ((TextCell)d)._gcr.horizontal_content_alignment = (HorizontalAlignment)e.NewValue));
if (e.OldValue is HorizontalAlignment oldha) {
if (oldha == HorizontalAlignment.Right) {
}
}
((TextCell)d)._gcr.horizontal_content_alignment = (HorizontalAlignment)e.NewValue;
}));
public HorizontalAlignment HorizontalContentAlignment { public HorizontalAlignment HorizontalContentAlignment {
get => (HorizontalAlignment)GetValue(HorizontalContentAlignmentProperty); get => (HorizontalAlignment)GetValue(HorizontalContentAlignmentProperty);
@@ -130,7 +131,8 @@ namespace mbts.ui.controls {
public static readonly DependencyProperty VerticalContentAlignmentProperty = Control.VerticalContentAlignmentProperty.AddOwner(typeof(TextCell), public static readonly DependencyProperty VerticalContentAlignmentProperty = Control.VerticalContentAlignmentProperty.AddOwner(typeof(TextCell),
new FrameworkPropertyMetadata( new FrameworkPropertyMetadata(
VerticalAlignment.Center, VerticalAlignment.Center,
FrameworkPropertyMetadataOptions.AffectsArrange, FrameworkPropertyMetadataOptions.AffectsArrange |
FrameworkPropertyMetadataOptions.AffectsRender,
(d, e) => ((TextCell)d)._gcr.vertical_content_alignment = (VerticalAlignment)e.NewValue)); (d, e) => ((TextCell)d)._gcr.vertical_content_alignment = (VerticalAlignment)e.NewValue));
public VerticalAlignment VerticalContentAlignment { public VerticalAlignment VerticalContentAlignment {
@@ -237,35 +239,17 @@ namespace mbts.ui.controls {
return _gcr.layout_size; return _gcr.layout_size;
} }
double bl_x = 0;
protected override void OnRender(DrawingContext drawingContext) { protected override void OnRender(DrawingContext drawingContext) {
var rs = RenderSize; var rs = RenderSize;
var rect = new Rect(0, 0, rs.Width, rs.Height); var rect = new Rect(0, 0, rs.Width, rs.Height);
var bg = Background; var bg = Background;
if (bg != null) { drawingContext.DrawRectangle(bg, _border_stroke_pen, rect, _snaps_to_device_pixels);
drawingContext.DrawRectangle(bg, _border_stroke_pen, rect); var gr = _glyph_run;
} if (gr != null) {
if (_glyph_run != null) {
var new_x = _glyph_run.BaselineOrigin.X;
if (Math.Abs(bl_x - new_x) > 5) {
if (new_x < bl_x) {
}
}
if (Text == "-3,375.000") {
}
bl_x = new_x;
drawingContext.PushClip(new RectangleGeometry(rect)); drawingContext.PushClip(new RectangleGeometry(rect));
drawingContext.DrawGlyphRun(_foreground, _glyph_run); drawingContext.DrawGlyphRun(_foreground, gr);
drawingContext.Pop(); drawingContext.Pop();
} }
if (bg != null) {
var bgo = DIYGrid.GetBackgroundOverlay(this);
if (bgo != null)
drawingContext.DrawRectangle(bgo, null, rect);
}
} }
} }
} }
@@ -1,30 +1,76 @@
using System; using bts.utils;
using System;
using System.Collections.Generic;
using System.Windows; using System.Windows;
using System.Windows.Media; using System.Windows.Controls;
namespace mbts.ui.controls { namespace mbts.ui.controls {
// Column types are nested inside the DIYGrid // Column types are nested inside the DIYGrid
partial class DIYGrid { partial class DIYGrid {
public struct ColumnGeometry { public readonly struct CellGeometry {
public ColumnBase column; public CellGeometry(ColumnGeometry column, ListBoxItem row) {
public DIYGridSuperHeader super_column; this.column = column;
public double unclipped_left; /* If the column was unclipped */ this.row = row;
public double left; }
public double width { get { return column.ActualWidth; } }
public double right { get { return unclipped_left + width; } } public ColumnGeometry column { get; }
public ListBoxItem row { get; }
public void Deconstruct(out ListBoxItem row, out ColumnGeometry column) {
row = this.row;
column = this.column;
}
public Rect to_rect(double y) =>
column.to_visible_rect(row.ActualHeight, y);
public static implicit operator (ListBoxItem, ColumnGeometry) (CellGeometry cell) =>
(cell.row, cell.column);
}
public readonly struct ColumnGeometry : IComparable<ColumnGeometry> {
public static readonly IEqualityComparer<ColumnGeometry> PositionEqualityComparer =
EqualityComparer.Create<ColumnGeometry, (double, double)>(c => (c.left, c.right));
public readonly ColumnBase column;
public readonly DIYGridSuperHeader super_column;
public readonly double
left,
// If the column was unclipped
unclipped_left,
right;
public ColumnGeometry(ColumnBase column, DIYGridSuperHeader super_column, double left, double right)
: this(column, super_column, left, left, right) { }
public ColumnGeometry(ColumnBase column, DIYGridSuperHeader super_column, double left, double unclipped_left, double right) {
this.column = column;
this.super_column = super_column;
this.left = left;
this.unclipped_left = unclipped_left;
this.right = right;
}
public double width => right - left;
public bool is_partially_obscured { get { return unclipped_left < left; } } public bool is_partially_obscured { get { return unclipped_left < left; } }
public double visible_width => Math.Max(0, width - left + unclipped_left); public double visible_width => Math.Max(0, width - left + unclipped_left);
public string group { get { return super_column == null ? "" : super_column.FullHeader; } }
public Rect to_rect(double row_height) =>
new Rect(left, 0, width, row_height);
public Rect to_visible_rect(double row_height, double y) =>
new Rect(unclipped_left, y, visible_width, row_height);
public override string ToString() { public override string ToString() {
return "{3} {0:0.0},{1:0.0} w{2:0.0}".fmt(left, right, width, column.Header); return "{3} {0:0.0},{1:0.0} w{2:0.0}".fmt(left, right, width, column.Header);
} }
public string group { get { return super_column == null ? "" : super_column.FullHeader; } }
public RectangleGeometry get_clip(double row_height) => public int CompareTo(ColumnGeometry other) {
new RectangleGeometry(new Rect(left, 0, width - left + unclipped_left, row_height)); int comp = left.CompareTo(other.left);
if (comp != 0)
public IDisposable clip_draw(DrawingContext dc, double row_height) { return comp;
dc.PushClip(get_clip(row_height)); return right.CompareTo(other.right);
return Disposable.Create(dc.Pop);
} }
} }
} }
@@ -0,0 +1,108 @@
using mbts.utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace mbts.ui.controls {
class ColumnSortManager {
readonly List<DIYGrid.ColumnBase> _visible_sorting = new List<DIYGrid.ColumnBase>();
readonly IList<DIYGrid.ColumnBase> _columns;
readonly string _primary_key;
public ColumnSortManager(IList<DIYGrid.ColumnBase> columns, string primary_key) {
_columns = columns;
_primary_key = primary_key;
}
public IEnumerable<DIYGrid.ColumnBase> visible_sorting =>
_visible_sorting.AsEnumerable();
public IEnumerable<DIYGrid.ColumnBase> active_sorting {
get {
bool has_primary = false;
foreach (var col in _visible_sorting) {
if (!has_primary && col.id == _primary_key) {
has_primary = true;
}
yield return col;
}
if (!has_primary) {
var pcol = _find_column(_primary_key);
if (pcol != null)
yield return pcol;
}
}
}
public IEnumerable<SortingCriteria> create() {
foreach (var col in _visible_sorting) {
var dir = col.SortDirection;
if (dir.HasValue)
yield return new SortingCriteria(col.id, dir.Value == ListSortDirection.Ascending);
}
}
public void load(IEnumerable<SortingCriteria> sorting_criterion) {
_clear();
foreach (var sc in sorting_criterion) {
var col = _find_column(sc.col_name);
if (col != null) {
col.SortDirection = sc.direction();
_visible_sorting.Add(col);
}
}
}
public void on_column_click(string id, bool is_shift_pressed) =>
on_column_click(_find_column(id), is_shift_pressed);
public void on_column_click(DIYGrid.ColumnBase col, bool is_shift_pressed) {
if (col == null)
return;
var old_dir = col.SortDirection;
if (!is_shift_pressed) {
_clear();
col.SortDirection = _reverse(old_dir);
_visible_sorting.Add(col);
} else {
col.SortDirection = _reverse(old_dir);
if (!old_dir.HasValue)
_visible_sorting.Add(col);
}
}
static ListSortDirection _reverse(ListSortDirection? dir) =>
dir.HasValue && dir.Value == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
void _clear() {
_visible_sorting.Clear();
foreach (var c in _columns)
c.SortDirection = null;
}
DIYGrid.ColumnBase _find_column(string id) =>
_columns.FirstOrDefault(c => c.id == id);
}
static class ColumnSortManagerExtensions {
public static IComparer<TRow> build_comparer<TColumnKey, TRow>(
this ColumnSortManager sort_manager,
Func<TColumnKey, IComparer<TRow>> get_column_comparer)
where TColumnKey : struct {
//
var bd = new ComparerBuilder<TRow>();
foreach (var col in sort_manager.active_sorting) {
if (Enum.TryParse(col.id, true, out TColumnKey key)) {
var dir = col.SortDirection;
if (dir.HasValue) {
var comp = get_column_comparer(key);
if (comp != null)
bd.add(DIYGridSortHelper.reverse_if_descending(comp, dir.Value));
}
}
}
return bd.to_comparer();
}
}
}
@@ -1,40 +1,65 @@
using mbts.spark.filters; using mbts.spark.filters;
using mbts.ui.converters; using mbts.ui.converters;
using System;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
namespace mbts.ui.controls { namespace mbts.ui.controls {
partial class DIYGrid { partial class DIYGrid {
internal class HyperlinkElementColumn<TRowVM, TKey> : FrameworkElementColumnBase<TKey>, IFrameworkElementColumn, IFilterableColumn, IKeyedColumn<TKey> { internal class HyperlinkElementColumn<TKey> : ColumnBase<TKey>, IFrameworkElementColumn, IFilterableColumn, IKeyedColumn<TKey> {
static readonly Thickness _default_padding = new Thickness(6, 0, 6, 0); public HyperlinkElementColumn(TKey key, IDataGridColumnFilter filter, string filter_template)
readonly BindingBase _binding, _command_binding; : base(key) {
public HyperlinkElementColumn(
TKey key, BindingBase binding, BindingBase command_binding, IDataGridColumnFilter filter, string filter_template) : base(key) {
this.filter = filter; this.filter = filter;
this.filter_template = filter_template; this.filter_template = filter_template;
_binding = binding;
_command_binding = command_binding;
} }
public IDataGridColumnFilter filter { get; } public event Action<HyperlinkCell> view_generated;
public string filter_template { get; }
public Thickness padding { get; set; } = _default_padding; public Style ElementStyle { get; set; }
public IDataGridColumnFilter filter { get; set; }
public override FrameworkElement view_factory() { public string filter_template { get; set; }
var hl = new HyperlinkCell { Padding = padding }; // bindings
public BindingBase CommandBinding { get; set; }
public BindingBase CommandParameterBinding { get; set; }
public BindingBase TextBinding { get; set; }
public FrameworkElement view_factory() {
var hl = new HyperlinkCell();
hl.SetCurrentValue(DIYGrid.ColumnProperty, this);
// bindings
if (TextBinding != null)
hl.SetBinding(HyperlinkCell.TextProperty, TextBinding);
if (CommandBinding != null)
hl.SetBinding(HyperlinkCell.CommandProperty, CommandBinding);
if (CommandParameterBinding != null)
hl.SetBinding(HyperlinkCell.CommandParameterProperty, CommandParameterBinding);
hl.SetBinding(HyperlinkCell.ForegroundProperty, new Binding(nameof(font_brush)) { Source = this }); hl.SetBinding(HyperlinkCell.ForegroundProperty, new Binding(nameof(font_brush)) { Source = this });
hl.SetBinding(HyperlinkCell.TextProperty, _binding);
hl.SetBinding(HyperlinkCell.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this }); hl.SetBinding(HyperlinkCell.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this });
hl.SetBinding(HyperlinkCell.FontSizeProperty, new Binding(nameof(font_size)) { Source = this }); hl.SetBinding(HyperlinkCell.FontSizeProperty, new Binding(nameof(font_size)) { Source = this });
hl.SetBinding(HyperlinkCell.HorizontalAlignmentProperty, new Binding(nameof(horizontal_alignment)) { Source = this }); hl.SetBinding(HyperlinkCell.HorizontalContentAlignmentProperty, new Binding(nameof(horizontal_alignment)) { Source = this });
hl.SetBinding(HyperlinkCell.CommandProperty, _command_binding); hl.SetBinding(FrameworkElement.WidthProperty, new Binding(nameof(ActualWidth)) { Source = this });
hl.SetBinding(HyperlinkCell.WidthProperty, new Binding(nameof(ActualWidth)) { Source = this }); hl.SetBinding(
hl.SetBinding(HyperlinkCell.BackgroundProperty, new Binding(nameof(background_brush)) { Source = this }); CursorProperty,
new Binding {
Source = hl,
Path = new PropertyPath(HyperlinkCell.IsMouseOverClickAreaProperty),
Converter = new BooleanToObjectConverter {
ValueForFalse = Cursors.Arrow,
ValueForTrue = Cursors.Hand
}
});
// background
var bg_brush = new SolidColorBrush();
BindingOperations.SetBinding(bg_brush, SolidColorBrush.ColorProperty, new Binding(nameof(background_color)) { Source = this });
hl.SetCurrentValue(HyperlinkCell.BackgroundProperty, bg_brush);
// style
if (ElementStyle != null)
hl.Style = ElementStyle;
view_generated?.Invoke(hl);
return hl; return hl;
} }
} }
} }
} }
@@ -1,44 +1,50 @@
using mbts.spark.filters; using mbts.spark.filters;
using System.Windows; using System.Windows;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Media;
namespace mbts.ui.controls { namespace mbts.ui.controls {
partial class DIYGrid { partial class DIYGrid {
internal class TextColumn<TColKey> : FrameworkElementColumnBase<TColKey>, IFilterableColumn { internal class TextColumn<TKey> : FrameworkElementColumnBase<TKey>, IFrameworkElementColumn, IFilterableColumn, IKeyedColumn<TKey> {
readonly BindingBase _binding; static readonly Thickness _default_padding = new Thickness(6, 0, 6, 0);
public TextColumn(TColKey key, BindingBase binding, IDataGridColumnFilter filter, string filter_template) : base(key) { public TextColumn(
TKey key, IDataGridColumnFilter filter, string filter_template) : base(key) {
this.filter = filter; this.filter = filter;
this.filter_template = filter_template; this.filter_template = filter_template;
_binding = binding;
} }
public Style ElementStyle { get; set; }
public IDataGridColumnFilter filter { get; } public IDataGridColumnFilter filter { get; }
public string filter_template { get; } public string filter_template { get; }
public BindingBase background_binding { get; set; } public Thickness padding { get; set; } = _default_padding;
public BindingBase font_weight_binding { get; set; } // bindings
public BindingBase foreground_binding { get; set; } public BindingBase TextBinding { get; set; }
public BindingBase tooltip_binding { get; set; } public BindingBase ToolTipBinding { get; set; }
public VerticalAlignment vertical_alignment { get; set; } = VerticalAlignment.Center;
public override FrameworkElement view_factory() { public override FrameworkElement view_factory() {
var v = new TextCell { Foreground = font_brush, VerticalAlignment = vertical_alignment }; var v = new TextCell {
v.SetBinding(TextCell.TextProperty, _binding); Padding = padding
};
// bindings
if (TextBinding != null)
v.SetBinding(TextCell.TextProperty, TextBinding);
if (ToolTipBinding != null)
v.SetBinding(ToolTipProperty, ToolTipBinding);
v.SetBinding(TextCell.ForegroundProperty, new Binding(nameof(font_brush)) { Source = this });
v.SetBinding(TextCell.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this }); v.SetBinding(TextCell.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this });
v.SetBinding(TextCell.FontSizeProperty, new Binding(nameof(font_size)) { Source = this }); v.SetBinding(TextCell.FontSizeProperty, new Binding(nameof(font_size)) { Source = this });
v.SetBinding(TextCell.HorizontalAlignmentProperty, new Binding(nameof(horizontal_alignment)) { Source = this }); v.SetBinding(TextCell.HorizontalContentAlignmentProperty, new Binding(nameof(horizontal_alignment)) { Source = this });
v.SetBinding(TextCell.WidthProperty, new Binding(nameof(ActualWidth)) { Source = this }); v.SetBinding(FrameworkElement.WidthProperty, new Binding(nameof(ActualWidth)) { Source = this });
try_set_binding(TextCell.BackgroundProperty, background_binding); // background
try_set_binding(TextCell.ForegroundProperty, foreground_binding); var bg_brush = new SolidColorBrush();
try_set_binding(TextCell.FontWeightProperty, font_weight_binding); BindingOperations.SetBinding(bg_brush, SolidColorBrush.ColorProperty, new Binding(nameof(background_color)) { Source = this });
try_set_binding(TextCell.ToolTipProperty, tooltip_binding); v.Background = bg_brush;
// style
if (ElementStyle != null)
v.Style = ElementStyle;
return v; return v;
//
void try_set_binding(DependencyProperty p, BindingBase b) {
if (b != null)
v.SetBinding(p, b);
}
} }
} }
} }
} }
+395 -106
View File
@@ -1,9 +1,11 @@
using bts; using bts;
using bts.collections;
using bts.utils; using bts.utils;
using mbts.spark.filters; using mbts.spark.filters;
using mbts.ui.controls.adorners; using mbts.ui.controls.adorners;
using mbts.ui.converters;
using mbts.ui.dpi;
using mbts.ui.extensions; using mbts.ui.extensions;
using mbts.ui.settings;
using mbts.ui.utility; using mbts.ui.utility;
using mbts.utils; using mbts.utils;
using System; using System;
@@ -22,6 +24,7 @@ using System.Windows.Controls.Primitives;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Shapes;
namespace mbts.ui.controls { namespace mbts.ui.controls {
interface IHandleGridSorting { interface IHandleGridSorting {
@@ -74,6 +77,26 @@ namespace mbts.ui.controls {
} }
} }
public static void reset_sorting<TKey>(IEnumerable<DIYGrid.ColumnBase> columns, IEnumerable<SortingCriteria> sorting_criterion) where TKey : struct =>
reset_sorting(columns, convert_sorting_criterion<TKey>(sorting_criterion));
public static void reset_sorting<TKey>(IEnumerable<DIYGrid.ColumnBase> columns, IEnumerable<(TKey key, ListSortDirection direction)> sorting_hierarchy) where TKey : struct {
// TODO: incorporate the sort hierarchy/index, for nested sorting
var active_cols = sorting_hierarchy.empty_if_null()
.Select((k, i) => (k, i))
.ToDictionary(tup => tup.k.key, tup => (tup.k.direction, tup.i));
// columns are dispatcher objects, and might throw if they are accessed after the view has been shut down
try {
foreach (var c in columns) {
if (Enum.TryParse(c.id, true, out TKey key) && active_cols.TryGetValue(key, out var tup)) {
c.SortDirection = tup.direction;
} else {
c.SortDirection = null;
}
}
} catch { }
}
public static IObservable<ImmutableList<(TKey key, IComparer<TRow> comparer, ListSortDirection direction)>> observe_active_comparers<TKey, TRow>( public static IObservable<ImmutableList<(TKey key, IComparer<TRow> comparer, ListSortDirection direction)>> observe_active_comparers<TKey, TRow>(
DIYGrid grid, Func<TKey, IComparer<TRow>> get_comparer, bool mark_handled = true) => DIYGrid grid, Func<TKey, IComparer<TRow>> get_comparer, bool mark_handled = true) =>
// //
@@ -202,24 +225,39 @@ namespace mbts.ui.controls {
} }
class DIYGridRowsPresenter : ListBox { class DIYGridRowsPresenter : ListBox {
static readonly PropertyPath
_highlight_path = new PropertyPath(DIYGrid.SelectionHighlightProperty),
_active_path = new PropertyPath(IsSelectionActiveProperty);
static readonly IValueConverter
_active_opacity_converter = ValueConverter.create<bool, double>(is_active => is_active ? 1.0 : 0.5);
readonly LoggerContext _log = new LoggerContext(Log.Ui, $"{nameof(DIYGridRowsPresenter)} ", null); readonly LoggerContext _log = new LoggerContext(Log.Ui, $"{nameof(DIYGridRowsPresenter)} ", null);
double _row_height = DIYGrid.DefaultRowHeight; double _row_height = DIYGrid.DefaultRowHeight;
ScrollContentPresenter _content_presenter_backing; ScrollContentPresenter _content_presenter_backing;
DIYGrid _grid; DIYGrid _grid;
DragRectAdorner _drag_rect_adorner; AdornerHost<Rectangle> _drag_rect_adorner;
RowSelectionAdorner _rsa; RowSelectionAdorner _rsa;
DIYGridCellHoverAdorner _cell_hover_adorner;
ScrollViewer _scroll_viewer; ScrollViewer _scroll_viewer;
Point? _drag_start; Point? _drag_start, _drag_stop;
double _drag_start_vertical_drift; double
_drag_start_horizontal_drift,
_drag_start_vertical_drift;
bool _support_group_items; bool _support_group_items;
int _drag_start_index; int _drag_start_index;
object _drag_start_item; object _drag_start_item;
IDisposable _drag_hook;
static DIYGridRowsPresenter() => static DIYGridRowsPresenter() =>
DefaultStyleKeyProperty.OverrideMetadata(typeof(DIYGridRowsPresenter), new FrameworkPropertyMetadata(typeof(DIYGridRowsPresenter))); DefaultStyleKeyProperty.OverrideMetadata(typeof(DIYGridRowsPresenter), new FrameworkPropertyMetadata(typeof(DIYGridRowsPresenter)));
public DIYGridRowsPresenter() { public DIYGridRowsPresenter() {
Loaded += (s, e) => { Loaded += on_loaded;
Unloaded += on_unloaded;
//
void on_loaded(object sender, RoutedEventArgs e) {
destroy_state();
if (_grid != null) if (_grid != null)
_grid.RowHeightChanged -= on_row_height_changed; _grid.RowHeightChanged -= on_row_height_changed;
_grid = this.find_ancestor_of_type<DIYGrid>(); _grid = this.find_ancestor_of_type<DIYGrid>();
@@ -228,25 +266,61 @@ namespace mbts.ui.controls {
_support_group_items = _grid.SupportGroupItems; _support_group_items = _grid.SupportGroupItems;
_grid.SupportGroupItemsChanged += on_support_group_items_changed; _grid.SupportGroupItemsChanged += on_support_group_items_changed;
_scroll_viewer = this.descendants_of_type<ScrollViewer>().First(); _scroll_viewer = this.descendants_of_type<ScrollViewer>().First();
if (SelectionMode != SelectionMode.Single) { // selection highlighting
_drag_rect_adorner = new DragRectAdorner(this, _scroll_viewer, _row_height);
_drag_rect_adorner.SetResourceReference(DragRectAdorner.FillProperty, DIYGrid.ActiveSelectionHighlightKey);
_drag_rect_adorner.SetResourceReference(DragRectAdorner.StrokeProperty, DIYGrid.SelectionStrokeKey);
_drag_rect_adorner.attach();
}
_rsa = new RowSelectionAdorner(this, _scroll_viewer); _rsa = new RowSelectionAdorner(this, _scroll_viewer);
_rsa.bind(RowSelectionAdorner.FillProperty, _highlight_path, DIYGrid.SelectionHighlightBrushConverter, _grid);
_rsa.bind(RowSelectionAdorner.StrokeProperty, _highlight_path, DIYGrid.SelectionHighlightPenConverter, _grid);
_rsa.bind(OpacityProperty, _active_path, DIYGrid.SelectionHighlightOpacityConverter, this);
_rsa.attach(); _rsa.attach();
}; // cell hover adorner
Unloaded += (s, e) => { _cell_hover_adorner = new DIYGridCellHoverAdorner(this, _scroll_viewer);
_cell_hover_adorner.SetBinding(VisibilityProperty, new Binding {
Path = new PropertyPath(IsMouseOverProperty),
Converter = new converters.BooleanToVisibilityConverter(),
Source = this
});
// drag
_drag_hook = Disposable.Create(
DragDropHelper.subscribe_drag_coordinates(this, init_element: _content_presenter, use_preview_events: true)
.Subscribe(pt => {
if (_drag_start.HasValue) {
if (pt.HasValue) {
_drag_stop = pt.Value;
_refresh_drag_rect();
} else {
if (_drag_stop.HasValue) {
_end_drag(_drag_stop.Value);
}
_drag_start = null;
_drag_stop = null;
}
} else if (pt.HasValue) {
_begin_drag_selection(pt.Value);
}
}),
_scroll_viewer.SubscribeScrollChanged((s, _) => _refresh_drag_rect()));
}
void on_unloaded(object sender, RoutedEventArgs e) =>
destroy_state();
// idempotent
void destroy_state() {
Disposable.dispose(ref _drag_hook);
if (_drag_rect_adorner != null) { if (_drag_rect_adorner != null) {
_drag_rect_adorner.detach(); _drag_rect_adorner.detach();
Disposable.dispose(ref _drag_rect_adorner); _drag_rect_adorner = null;
} }
if (_rsa != null) { if (_rsa != null) {
_rsa.detach(); _rsa.detach();
Disposable.dispose(ref _rsa); Disposable.dispose(ref _rsa);
} }
}; if (_cell_hover_adorner != null) {
_cell_hover_adorner.detach();
Disposable.dispose(ref _cell_hover_adorner);
}
}
void on_row_height_changed(double v) => _row_height = v; void on_row_height_changed(double v) => _row_height = v;
void on_support_group_items_changed(bool v) => _support_group_items = v; void on_support_group_items_changed(bool v) => _support_group_items = v;
} }
@@ -264,8 +338,8 @@ namespace mbts.ui.controls {
base.UnselectAll(); base.UnselectAll();
} }
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) { void _begin_drag_selection(Point pt) {
var pt = e.GetPosition(this); _drag_rect_adorner?.detach();
if (InputHitTest(pt) is UIElement el) { if (InputHitTest(pt) is UIElement el) {
var sb = new StringBuilderEx("beginning drag selection on "); var sb = new StringBuilderEx("beginning drag selection on ");
OneOf.MatchFirst<DependencyObject, ListBoxItem, GroupItem>(el.VisualAncestors().Prepend(el)).Match(init_common, on_group); OneOf.MatchFirst<DependencyObject, ListBoxItem, GroupItem>(el.VisualAncestors().Prepend(el)).Match(init_common, on_group);
@@ -279,22 +353,43 @@ namespace mbts.ui.controls {
} }
} }
void init_common(ListBoxItem item_container) { void init_common(ListBoxItem item_container) {
// drag state
_drag_start = pt; _drag_start = pt;
_drag_stop = pt;
_drag_start_item = ItemContainerGenerator.ItemFromContainer(item_container); _drag_start_item = ItemContainerGenerator.ItemFromContainer(item_container);
_drag_start_index = ItemContainerGenerator.IndexFromContainer(item_container); _drag_start_index = ItemContainerGenerator.IndexFromContainer(item_container);
_drag_start_horizontal_drift = _scroll_viewer.HorizontalOffset;
_drag_start_vertical_drift = _scroll_viewer.VerticalOffset; _drag_start_vertical_drift = _scroll_viewer.VerticalOffset;
if (!IsKeyboardFocusWithin)
Keyboard.Focus(item_container);
// drag rect
_drag_rect_adorner = new AdornerHost<Rectangle>(_content_presenter ?? (UIElement)this) {
Child = new Rectangle {
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
StrokeThickness = HighDpiExtensions.pixel_unit
},
IsClipEnabled = true
};
_drag_rect_adorner.Child.bind(Shape.FillProperty, _highlight_path, DIYGrid.SelectionHighlightBrushConverter, _grid);
_drag_rect_adorner.Child.bind(Shape.StrokeProperty, _highlight_path, DIYGrid.SelectionHighlightOpaqueBrushConverter, _grid);
_refresh_drag_rect();
_drag_rect_adorner.attach();
// log
sb.Add($"'{_drag_start_item}' (selection mode {SelectionMode})."); sb.Add($"'{_drag_start_item}' (selection mode {SelectionMode}).");
_log.info(sb.ToString()); _log.info(sb.ToString());
} }
} }
base.OnPreviewMouseLeftButtonDown(e);
} }
protected override void OnPreviewMouseUp(MouseButtonEventArgs e) { void _end_drag(Point drag_stop) {
if (_drag_rect_adorner != null) {
_drag_rect_adorner.detach();
_drag_rect_adorner = null;
}
if (_drag_start.HasValue) { if (_drag_start.HasValue) {
_log.info("ending drag selection on mouse up."); _log.info("ending drag selection on mouse up.");
if (SelectionMode != SelectionMode.Single && _content_presenter != null) { if (SelectionMode != SelectionMode.Single && _content_presenter != null) {
var drag_stop = e.GetPosition(this);
drag_stop.X = MathUtils.within_range(0, _content_presenter.RenderSize.Width - 1, drag_stop.X); drag_stop.X = MathUtils.within_range(0, _content_presenter.RenderSize.Width - 1, drag_stop.X);
drag_stop.Y = MathUtils.within_range(0, _content_presenter.RenderSize.Height - 1, drag_stop.Y); drag_stop.Y = MathUtils.within_range(0, _content_presenter.RenderSize.Height - 1, drag_stop.Y);
double vertical_diff = drag_stop.Y + (_row_height * (_scroll_viewer.VerticalOffset - _drag_start_vertical_drift)) - _drag_start.Value.Y; double vertical_diff = drag_stop.Y + (_row_height * (_scroll_viewer.VerticalOffset - _drag_start_vertical_drift)) - _drag_start.Value.Y;
@@ -356,7 +451,22 @@ namespace mbts.ui.controls {
_drag_start = null; _drag_start = null;
_drag_start_item = null; _drag_start_item = null;
} }
base.OnPreviewMouseUp(e); }
void _refresh_drag_rect() {
if (_drag_rect_adorner == null || !_drag_start.HasValue || !_drag_stop.HasValue)
return;
var hdiff = _scroll_viewer.HorizontalOffset - _drag_start_horizontal_drift;
var vdiff = _scroll_viewer.VerticalOffset - _drag_start_vertical_drift;
var rect = new Rect(
new Point(_drag_start.Value.X - hdiff, _drag_start.Value.Y - vdiff * _grid.RowHeight),
_drag_stop.Value);
if (rect.IsEmpty)
return;
rect.Intersect(this.GetChildBounds(_drag_rect_adorner.AdornedElement));
_drag_rect_adorner.Child.Margin = new Thickness(rect.Left, rect.Top, 0, 0);
_drag_rect_adorner.Child.Width = rect.Width;
_drag_rect_adorner.Child.Height = rect.Height;
} }
void _select_items_between(object inclusive_begin, object inclusive_end) { void _select_items_between(object inclusive_begin, object inclusive_end) {
@@ -378,10 +488,6 @@ namespace mbts.ui.controls {
} }
partial class DIYGrid : Control { partial class DIYGrid : Control {
public const string
ActiveSelectionHighlightKey = nameof(ActiveSelectionHighlightKey),
InactiveSelectionHighlightKey = nameof(InactiveSelectionHighlightKey),
SelectionStrokeKey = nameof(SelectionStrokeKey);
public const double public const double
DefaultRowHeight = 17, DefaultRowHeight = 17,
DefaultColumnHeaderHeight = 30; DefaultColumnHeaderHeight = 30;
@@ -411,55 +517,47 @@ namespace mbts.ui.controls {
// TODO: SelectionFill/Stroke should not be hardcoded, for now this serves as the central location for DragRectAdorner, // TODO: SelectionFill/Stroke should not be hardcoded, for now this serves as the central location for DragRectAdorner,
// and FrameworkElementColumns that paint the selection brush themselves // and FrameworkElementColumns that paint the selection brush themselves
// (e.g MarketView bid/ask columns, bc their background is not transparent, it covers the ListBoxItem selection-highlight). // (e.g MarketView bid/ask columns, bc their background is not transparent, it covers the ListBoxItem selection-highlight).
public static readonly SolidColorBrush DefaultSelectionHighlight = new SolidColorBrush(Colors.MediumSlateBlue) { Opacity = 0.4 }; public static readonly Color DefaultSelectionHighlight = Colors.MediumSlateBlue.with(0x63);
public static readonly Pen DefaultSelectionStroke = new Pen(Brushes.MediumSlateBlue, 1);
readonly NotifyCollectionChangedEventHandler _sort_descriptions_collection_changed_cb; readonly NotifyCollectionChangedEventHandler _sort_descriptions_collection_changed_cb;
double _inactive_selection_opacity = 0.2;
DataContextHooks _data_context_hooks; DataContextHooks _data_context_hooks;
public static readonly DependencyProperty SelectionHighlightProperty = public static readonly DependencyProperty SelectionHighlightProperty =
WPFHelper.create_dp<SolidColorBrush, DIYGrid>( WPFHelper.create_dp<Color, DIYGrid>(nameof(SelectionHighlight), DefaultSelectionHighlight);
nameof(SelectionHighlight),
(o, v) => {
o.Resources[ActiveSelectionHighlightKey] = v;
o._reset_inactive_selection_brush();
o.Resources[SelectionStrokeKey] = new Pen(o.SelectionHighlight.Color.to_solid_brush().frozen(), 1).frozen();
foreach (var col in o.Columns.empty_if_null().OfType<ISelectionHighlightListener>())
col.on_selection_fill(v);
var ad_layer = System.Windows.Documents.AdornerLayer.GetAdornerLayer(o);
if (ad_layer != null) {
foreach (var ad in ad_layer.descendants_of_type<ISelectionHighlightListener>()) {
ad.on_selection_fill(v);
}
}
}, (o, v) => v as SolidColorBrush ?? DefaultSelectionHighlight,
DefaultSelectionHighlight);
public SolidColorBrush SelectionHighlight { public Color SelectionHighlight {
get => GetValue(SelectionHighlightProperty) as SolidColorBrush; get => (Color)GetValue(SelectionHighlightProperty);
set => SetValue(SelectionHighlightProperty, value); set => SetValue(SelectionHighlightProperty, value);
} }
static DIYGrid() { static DIYGrid() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(DIYGrid), new FrameworkPropertyMetadata(typeof(DIYGrid))); DefaultStyleKeyProperty.OverrideMetadata(typeof(DIYGrid), new FrameworkPropertyMetadata(typeof(DIYGrid)));
DefaultSelectionHighlight.Freeze(); UseLayoutRoundingProperty.OverrideMetadata(typeof(DIYGrid), new FrameworkPropertyMetadata(OnUseLayoutRoundingChanged));
DefaultSelectionStroke.Freeze();
void OnUseLayoutRoundingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
d.CoerceValue(RowHeightProperty);
} }
public DIYGrid() { public DIYGrid() {
var sort_map = new Dictionary<string, ColumnBase>(); var sort_map = new Dictionary<string, ColumnBase>();
_sort_descriptions_collection_changed_cb = WPFHelper.create_collection_changed_cb<SortDescription>( _sort_descriptions_collection_changed_cb = WPFHelper.create_collection_changed_cb<SortDescription>(
sd => { sd => {
if (!SyncColumnSortDirectionWithSortDescriptions)
return;
if (Columns.TryGetFirst(c => c.sort_member_path == sd.PropertyName, out ColumnBase col)) { if (Columns.TryGetFirst(c => c.sort_member_path == sd.PropertyName, out ColumnBase col)) {
sort_map[sd.PropertyName] = col; sort_map[sd.PropertyName] = col;
col.SortDirection = sd.Direction; col.SortDirection = sd.Direction;
} }
}, sd => { }, sd => {
if (!SyncColumnSortDirectionWithSortDescriptions)
return;
if (Columns.TryGetFirst(c => c.sort_member_path == sd.PropertyName, out ColumnBase col)) { if (Columns.TryGetFirst(c => c.sort_member_path == sd.PropertyName, out ColumnBase col)) {
col.SortDirection = null; col.SortDirection = null;
sort_map.Remove(sd.PropertyName); sort_map.Remove(sd.PropertyName);
} }
}, s => { }, s => {
if (!SyncColumnSortDirectionWithSortDescriptions)
return;
sort_map.Clear(); sort_map.Clear();
if (Columns is IEnumerable<ColumnBase> cols) { if (Columns is IEnumerable<ColumnBase> cols) {
foreach (var c in cols) foreach (var c in cols)
@@ -505,8 +603,6 @@ namespace mbts.ui.controls {
} }
} }
})); }));
Resources[ActiveSelectionHighlightKey] = SelectionHighlight;
_reset_inactive_selection_brush();
_data_context_hooks = new DataContextHooks(this, DataContext); _data_context_hooks = new DataContextHooks(this, DataContext);
DataContextChanged += OnDataContextChanged; DataContextChanged += OnDataContextChanged;
} }
@@ -514,15 +610,26 @@ namespace mbts.ui.controls {
public event DIYGridSortingEventHandler Sorting; public event DIYGridSortingEventHandler Sorting;
public event Action<bool> SupportGroupItemsChanged; public event Action<bool> SupportGroupItemsChanged;
public double InactiveSelectionOpacity { public static IValueConverter SelectionHighlightPenConverter =>
get => _inactive_selection_opacity; ValueConverter.create<Color, Pen>(c => FrozenPenCache.get_pen(c.with(255)));
set {
if (value != _inactive_selection_opacity && value.is_within_range(0.1, 0.9)) { public static IValueConverter SelectionHighlightBrushConverter =>
_inactive_selection_opacity = value; ValueConverter.create<Color, Brush>(FrozenBrushCache.get_brush);
_reset_inactive_selection_brush();
} public static IValueConverter SelectionHighlightOpaqueBrushConverter =>
} ValueConverter.create<Color, Brush>(c => FrozenBrushCache.get_brush(c.with(255)));
}
public static IValueConverter SelectionHighlightOpacityConverter =>
ValueConverter.create<bool, double>(is_active => is_active ? 1.0 : 0.5);
public static IValueConverter RowHoverHighlightBrushConverter =>
ValueConverter.create<Color, Brush>(c => FrozenBrushCache.get_brush(c, 0.35));
public static IValueConverter CellHoverHighlightPenConverter =>
ValueConverter.create<Color, Pen>(c => FrozenPenCache.get_pen(c.with(255)));
public static IValueConverter CellHoverHighlightBrushConverter =>
ValueConverter.create<Color, Brush>(c => FrozenBrushCache.get_brush(c, 0.5));
public bool SupportGroupItems { public bool SupportGroupItems {
get => _support_group_items; get => _support_group_items;
@@ -534,6 +641,8 @@ namespace mbts.ui.controls {
} }
} }
public bool SyncColumnSortDirectionWithSortDescriptions { get; set; } = true;
public ItemContainerGenerator RowContainerGenerator => public ItemContainerGenerator RowContainerGenerator =>
_row_presenter.ItemContainerGenerator; _row_presenter.ItemContainerGenerator;
@@ -582,18 +691,6 @@ namespace mbts.ui.controls {
void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) => void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) =>
Disposable.replace(ref _data_context_hooks, new DataContextHooks(this, e.NewValue)); Disposable.replace(ref _data_context_hooks, new DataContextHooks(this, e.NewValue));
void _reset_inactive_selection_brush() {
try {
if (TryFindResource(ActiveSelectionHighlightKey) is SolidColorBrush brush) {
var clone = brush.Clone();
if (_inactive_selection_opacity < clone.Opacity) {
clone.Opacity = _inactive_selection_opacity;
}
Resources[InactiveSelectionHighlightKey] = clone;
}
} catch { }
}
#region Column Handling #region Column Handling
public void invalidate_column_layout(object sender = null, EventArgs args = null) { public void invalidate_column_layout(object sender = null, EventArgs args = null) {
var geometry = GetColumnGeometry().ToList(); var geometry = GetColumnGeometry().ToList();
@@ -833,6 +930,22 @@ namespace mbts.ui.controls {
// Public Properties // Public Properties
#region Public Properties #region Public Properties
#region Column
public static readonly DependencyProperty ColumnProperty =
DependencyProperty.RegisterAttached("Column", typeof(ColumnBase), typeof(DIYGrid));
public static ColumnBase GetColumn(DependencyObject d) => d.GetValue(ColumnProperty) as ColumnBase;
public static void SetColumn(DependencyObject d, ColumnBase value) => d.SetValue(ColumnProperty, value);
#endregion
#region Grid
public static readonly DependencyProperty GridProperty =
DependencyProperty.RegisterAttached("Grid", typeof(DIYGrid), typeof(DIYGrid));
public static DIYGrid GetGrid(DependencyObject d) => d.GetValue(GridProperty) as DIYGrid;
public static void SetGrid(DependencyObject d, DIYGrid value) => d.SetValue(GridProperty, value);
#endregion
#region ColumnKey #region ColumnKey
public static readonly DependencyProperty ColumnKeyProperty = public static readonly DependencyProperty ColumnKeyProperty =
DependencyProperty.RegisterAttached("ColumnKey", DependencyProperty.RegisterAttached("ColumnKey",
@@ -1069,7 +1182,7 @@ namespace mbts.ui.controls {
if (v < min_row_height) if (v < min_row_height)
return min_row_height; return min_row_height;
} }
return v; return o.UseLayoutRounding ? v.RoundLayoutValue() : v;
}, DefaultRowHeight); }, DefaultRowHeight);
public event Action<double> RowHeightChanged; public event Action<double> RowHeightChanged;
@@ -1090,14 +1203,11 @@ namespace mbts.ui.controls {
public static readonly DependencyProperty RowsProperty = public static readonly DependencyProperty RowsProperty =
WPFHelper.create_dp<IEnumerable, DIYGrid>( WPFHelper.create_dp<IEnumerable, DIYGrid>(
nameof(Rows), nameof(Rows),
(s, oldval, newval) => { (s, oldval, newval) =>
WPFHelper.manage_collection_change( WPFHelper.manage_collection_change(
(oldval as ICollectionView)?.SortDescriptions, (oldval as ICollectionView)?.SortDescriptions,
(newval as ICollectionView)?.SortDescriptions, (newval as ICollectionView)?.SortDescriptions,
s._sort_descriptions_collection_changed_cb, s._sort_descriptions_collection_changed_cb),
old_ncc => s._sort_descriptions_collection_changed_cb(old_ncc, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)),
new_ncc => s._sort_descriptions_collection_changed_cb(new_ncc, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, (IList)new_ncc)));
},
Enumerable.Empty<object>()); Enumerable.Empty<object>());
public DataTemplate RowTemplate { public DataTemplate RowTemplate {
@@ -1146,33 +1256,30 @@ namespace mbts.ui.controls {
double frozen_offset = 0; double frozen_offset = 0;
int vis_frozen_col_count = _get_visible_frozen_column_count(); int vis_frozen_col_count = _get_visible_frozen_column_count();
foreach (var col in _visible_columns.Take(vis_frozen_col_count)) { foreach (var col in _visible_columns.Take(vis_frozen_col_count)) {
yield return new ColumnGeometry() { double right = frozen_offset + col.ActualWidth;
column = col, right = right.RoundLayoutValue();
left = frozen_offset, yield return new ColumnGeometry(col, null, frozen_offset, frozen_offset, right);
unclipped_left = frozen_offset,
};
frozen_offset += col.ActualWidth; frozen_offset += col.ActualWidth;
} }
// frozen_offset will be off by 2 pixels because of the GridViewHeaderRowPresenter PaddingHeader (see c_PaddingHeaderMinWidth in referencesource) if (_frozen_column_count > 0) {
// We could use the _header_frozen.ActualWidth but due to the async nature of layout it get updated slightly too late // frozen_offset will be off by 2 pixels because of the GridViewHeaderRowPresenter PaddingHeader (see c_PaddingHeaderMinWidth in referencesource)
frozen_offset += 2; // We could use the _header_frozen.ActualWidth but due to the async nature of layout it get updated slightly too late
frozen_offset += 2;
}
// Adjust by scroll amount // Adjust by scroll amount
double offset = frozen_offset - (_scroll_horizontal.Value); double offset = frozen_offset - _scroll_horizontal.Value;
offset = offset.RoundLayoutValue();
int count = 0; int count = 0;
foreach (var col in _visible_columns.Skip(vis_frozen_col_count)) { foreach (var col in _visible_columns.Skip(vis_frozen_col_count)) {
double left = Math.Max(offset, frozen_offset); double left = Math.Max(offset, frozen_offset);
double right = offset + col.ActualWidth; double right = offset + col.ActualWidth;
right = right.RoundLayoutValue();
// If right < frozen_offset column is completely obscured // If right < frozen_offset column is completely obscured
if (include_obscured_cols || (right > frozen_offset && left <= ActualWidth)) { if (include_obscured_cols || (right > frozen_offset && left <= ActualWidth)) {
// fully visible // fully visible
yield return new ColumnGeometry() { yield return new ColumnGeometry(col, _superheader_column_index.ElementAtOrDefault(count), left, offset, right);
column = col,
super_column = _superheader_column_index.ElementAtOrDefault(count),
unclipped_left = offset,
left = left
};
} }
offset += col.ActualWidth; offset = right;
++count; ++count;
} }
} }
@@ -1419,19 +1526,201 @@ namespace mbts.ui.controls {
public static IObservable<T> SubscribeMouseHoverRow<T>(this DIYGrid grid, IEqualityComparer<T> comparer) where T : class => public static IObservable<T> SubscribeMouseHoverRow<T>(this DIYGrid grid, IEqualityComparer<T> comparer) where T : class =>
Observable.Create<T>(o => { Observable.Create<T>(o => {
T curr_row = null; T last_row = null;
return grid.SubscribeMouseHoverRowContainer().Subscribe(row_view => {
if (grid.RowContainerGenerator.ItemFromContainer(row_view) is T row && !comparer.Equals(row, last_row))
o.OnNext(last_row = row);
});
});
public static IObservable<ListBoxItem> SubscribeMouseHoverRowContainer(this DIYGrid grid) =>
Observable.Create<ListBoxItem>(o => {
bool busy = false, dirty = false;
ListBoxItem curr_row = null;
return Disposable.Create( return Disposable.Create(
grid.SubscribeMouseEnter(on_mouse_enter), grid.SubscribeMouseEnter(on_mouse),
grid.SubscribeMouseLeave(on_mouse_leave), grid.SubscribeMouseLeave(on_mouse),
grid.SubscribePreviewMouseMove(on_mouse_move)); grid.SubscribeMouseLeftButtonDown(on_mouse),
void on_mouse_enter(object sender, MouseEventArgs e) => refresh(); grid.SubscribeMouseLeftButtonUp(on_mouse),
void on_mouse_move(object sender, MouseEventArgs e) => refresh(); grid.SubscribeMouseMove(on_mouse));
void on_mouse_leave(object sender, MouseEventArgs e) => refresh(); void on_mouse(object sender, MouseEventArgs e) => refresh();
void refresh() { void refresh() {
T row = grid.ChildAtPoint<ListBoxItem>(Mouse.GetPosition(grid)) is var rview && rview != null ? grid.RowContainerGenerator.ItemFromContainer(rview) as T : null; if (busy) {
if (!comparer.Equals(curr_row, row)) dirty = true;
o.OnNext(curr_row = row); } else {
dirty = false;
busy = true;
do {
grid.Dispatcher.InvokeAsync(() => {
var row = grid.ChildAtPoint<ListBoxItem>(Mouse.GetPosition(grid));
if (row != curr_row)
o.OnNext(curr_row = row);
dirty = false;
});
} while (dirty);
busy = false;
}
} }
}); });
public static IObservable<DIYGrid.CellGeometry?> SubscribeMouseHoverCell(this DIYGrid grid) {
return Observable.Create<DIYGrid.CellGeometry?>(o => {
IDisposable row_mouse_hooks = null;
DIYGrid.CellGeometry? last_value = null;
var layout = grid.GetColumnGeometry().ToList();
var layout_x_pts = layout.WrapSelector(cg => cg.left, null);
ListBoxItem hover_row = null;
grid.ColumnLayoutChanged += on_layout;
var hover_sub = grid.SubscribeMouseHoverRowContainer().Subscribe(on_row_view);
return Disposable.Create(dispose);
//
void notify(MouseEventArgs e = null) {
if (hover_row == null || layout.Count == 0)
on_cell(null);
else {
var pt = e?.GetPosition(hover_row) ?? Mouse.GetPosition(hover_row);
int index = CollectionHelper.binary_search(layout_x_pts, pt.X);
if (index < 0)
index = ~index - 1;
if (index >= 0 && index < layout.Count) {
on_cell(new DIYGrid.CellGeometry(layout[index], hover_row));
} else {
on_cell(null);
}
}
}
void on_cell(DIYGrid.CellGeometry? cell) {
if (!cell.Equals(last_value))
o.OnNext(last_value = cell);
}
void on_row_view(ListBoxItem row_view) {
row_mouse_hooks?.Dispose();
hover_row = row_view;
row_mouse_hooks = row_view?.SubscribeMouseMove(on_mouse_change);
notify();
}
void on_layout(List<DIYGrid.ColumnGeometry> obj) {
layout = grid.GetColumnGeometry().ToList();
layout_x_pts = layout.WrapSelector(cg => cg.left, null);
notify();
}
void on_mouse_change(object sender, MouseEventArgs e) =>
notify(e);
void dispose() {
Disposable.dispose(ref hover_sub);
grid.ColumnLayoutChanged -= on_layout;
}
});
}
public static IObservable<(IEnumerable<DIYGrid.ColumnGeometry> columns, int row_start, int row_count)?> SubscribeCellDragRect(this DIYGrid grid) {
return Observable.Create<(IEnumerable<DIYGrid.ColumnGeometry> columns, int row_start, int row_count)?>(o => {
return grid.ConnectOnLoaded(init);
IDisposable init() {
if (!( grid.try_find_descendent_of_type(out DIYGridRowsPresenter presenter) && presenter.try_find_descendent_of_type(out ScrollViewer scroll) && scroll.try_find_descendent_of_type(out ScrollContentPresenter scroll_content)))
return null;
// init state
var value_container = new DistinctSubject<(IEnumerable<DIYGrid.ColumnGeometry> columns, int row_start, int row_count)?>();
double y_start_drift = 0;
var layout = new List<DIYGrid.ColumnGeometry>();
var layout_x_pts = layout.WrapSelector(cg => cg.left, null);
object _drag_start_item = null;
int _drag_start_index = -1;
Point? drag_start = null, drag_curr = null;
//
scroll.ScrollChanged += on_scroll;
grid.ColumnLayoutChanged += on_layout;
var drag_hook = DragDropHelper.subscribe_drag_coordinates(presenter, grid, use_preview_events: false, mouse_button: MouseButton.Right).Subscribe(pt => {
if (drag_start.HasValue) {
if (!pt.HasValue) {
drag_start = null;
drag_curr = null;
} else {
drag_curr = pt;
}
} else {
if (pt.HasValue) {
var item_container = presenter.ChildAtPoint<ListBoxItem>(pt.Value);
if (item_container == null) {
pt = null;
} else {
_drag_start_item = grid.RowContainerGenerator.ItemFromContainer(item_container);
_drag_start_index = grid.RowContainerGenerator.IndexFromContainer(item_container);
y_start_drift = scroll.VerticalOffset;
}
}
drag_start = pt;
drag_curr = pt;
}
refresh();
});
grid.PreviewMouseUp += (s, e) => e.Handled = e.ChangedButton == MouseButton.Right;
var sub = value_container.Subscribe(o);
return Disposable.Create(dispose);
void on_layout(List<DIYGrid.ColumnGeometry> new_layout) {
layout = new_layout;
layout_x_pts = layout.WrapSelector(cg => cg.left, null);
}
void on_scroll(object sender, ScrollChangedEventArgs e) {
if (drag_start.HasValue)
refresh();
}
void refresh() {
if (!drag_start.HasValue) {
value_container.OnNext(null);
return;
}
var (xstart, ystart) = drag_start.Value.deconstruct();
var (xstop, ystop) = drag_curr.Value.deconstruct();
xstart = MathUtils.within_range(0, presenter.ActualWidth, xstart);
var row_height = grid.RowHeight;
xstop = MathUtils.within_range(0, scroll_content.RenderSize.Width - 1, xstop);
ystop = MathUtils.within_range(0, scroll_content.RenderSize.Height - 1, ystop);
double vertical_diff = ystop + (row_height * (scroll.VerticalOffset - y_start_drift)) - ystart;
int start_index, n_items;
if (vertical_diff > 0) {
double first_item_partial_height = row_height - (ystart % row_height);
n_items = (int)Math.Ceiling((vertical_diff - first_item_partial_height) / row_height) + 1;
start_index = _drag_start_index;
int overflow = start_index + n_items - presenter.Items.Count;
if (overflow > 0)
n_items -= overflow;
} else {
double first_item_partial_height = ystart % row_height;
n_items = -(int)Math.Floor((vertical_diff + first_item_partial_height) / row_height) + 1;
start_index = _drag_start_index - n_items + 1;
if (start_index < 0) {
n_items += start_index;
start_index = 0;
}
}
if (n_items > 0) {
var colstart = find_col(xstart);
var colstop = find_col(xstop);
(colstart, colstop) = MathUtils.get_outliers(colstart, colstop);
(ystart, ystop) = MathUtils.get_outliers(ystart, ystop);
var cols = layout.WrapSubRange(colstart, colstop - colstart + 1);
value_container.OnNext((cols, start_index, n_items));
}
}
int find_col(double x) {
if (layout.Count == 0)
return -1;
int i = CollectionHelper.binary_search(layout, x, l => l.left);
if (i < 0) {
i = ~i - 1;
}
return MathUtils.within_range(0, layout.Count - 1, i);
}
void dispose() {
Disposable.dispose(ref sub);
grid.ColumnLayoutChanged -= on_layout;
}
}
});
}
} }
} }
@@ -0,0 +1,161 @@
using bts.utils;
using mbts.ui.controls;
using mbts.ui.dpi;
using mbts.ui.extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace mbts.ui.spark {
class DIYGridPopupManager {
readonly DIYGrid _grid;
readonly FrameworkElement _owner;
readonly ScrollContentPresenter _scroll_content;
readonly ICollection<Visual> _children;
public static DIYGridPopupManager create(FrameworkElement owner) =>
create(owner, new VisualCollectionWrapper(new VisualCollection(owner)));
public static DIYGridPopupManager create(FrameworkElement owner, ICollection<Visual> visual_children) =>
owner.try_find_descendent_of_type(out DIYGrid grid) &&
grid.try_find_descendent_of_type(out DIYGridRowsPresenter rows_presenter) &&
rows_presenter.try_find_descendent_of_type(out ScrollContentPresenter scroll_content) ?
new DIYGridPopupManager(owner, grid, scroll_content, visual_children) :
null;
DIYGridPopupManager(FrameworkElement owner, DIYGrid grid, ScrollContentPresenter scroll_content, ICollection<Visual> children) {
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
_grid = grid ?? throw new ArgumentNullException(nameof(grid));
_scroll_content = scroll_content ?? throw new ArgumentNullException(nameof(scroll_content));
_children = children;
}
public void show(FrameworkElement view) {
var layout = _grid.GetColumnGeometry().ToList();
if (layout.Count == 0)
return;
var x_origin = layout[0].unclipped_left;
var mouse_pos = Mouse.GetPosition(_scroll_content);
var col_index = CollectionHelper.binary_search(layout, mouse_pos.X + x_origin, cg => cg.left);
if (col_index < 0)
col_index = ~col_index - 1;
col_index = MathUtils.within_range(0, layout.Count - 1, col_index);
var col = layout[col_index];
// determine top left
var top_left = _scroll_content.PointToScreenPixels(
col.unclipped_left - x_origin,
Math.Ceiling(mouse_pos.Y / _grid.RowHeight) * _grid.RowHeight);
var popup = _mk_popup(_owner, view, top_left);
// attach to [parent] win
IDisposable win_hook = null, win_pos_hook = null;
Point last_pt = default;
bool initialized = false;
WindowStyle.AddUnsafeWindowChangedHandler(popup, on_unsafe_win_changed);
popup.SetBinding(WindowStyle.UnsafeWindowProperty, new Binding {
Path = new PropertyPath(WindowStyle.UnsafeWindowProperty),
Source = _owner,
Mode = BindingMode.OneWay
});
popup.Closed += on_closed;
void on_unsafe_win_changed(object sender, RoutedPropertyChangedEventArgs<Window> e) {
var win = e.NewValue;
Disposable.dispose(ref win_pos_hook);
if (win != null) {
if (!initialized) {
// The popup's offset is initialized to the screen coordinates (further adjustments are made according to the delta),
// so last_pt must be initialized to the window's top left.
last_pt = new Point(win.Left, win.Top);
initialized = true;
}
popup.SetCurrentValue(WindowStyle.UnsafeWindowProperty, win);
win_pos_hook = win.ObserveTopLeft()
.SubscribeOn(win.Dispatcher)
.ObserveOnDispatcher(DispatcherPriority.Normal)
.Subscribe(pt => {
popup.HorizontalOffset += pt.X - last_pt.X;
popup.VerticalOffset += pt.Y - last_pt.Y;
last_pt = pt;
});
}
}
void on_closed(object sender, EventArgs e) {
popup.Closed -= on_closed;
WindowStyle.RemoveUnsafeWindowChangedHandler(_owner, on_unsafe_win_changed);
Disposable.dispose(ref win_pos_hook);
Disposable.dispose(ref win_hook);
}
}
public async Task show_async(FrameworkElement view, int delay_measure_ms = 100) {
if (delay_measure_ms > 0)
await Task.Delay(delay_measure_ms);
view.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
show(view);
}
ZPopup _mk_popup(FrameworkElement owner, FrameworkElement view, Point offset) {
// popup
var popup = new ZPopup {
PlacementTarget = _grid,
Placement = PlacementMode.Absolute,
Child = view,
HorizontalOffset = offset.X,
VerticalOffset = offset.Y,
IsOpen = true,
StaysOpen = false
};
view.InputBindings.Add(new KeyBinding(ApplicationCommands.Close, Key.Escape, ModifierKeys.None));
view.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (s, e) => popup.IsOpen = false));
var hooks = Disposable.Create(
view.SubscribePreviewMouseDown(on_view_preview_mouse_down),
view.ConnectDataContext<IRequestViewClose>(rvc => {
rvc.RequestClose += on_request_close;
return Disposable.Create(() => rvc.RequestClose -= on_request_close);
void on_request_close(object sender, EventArgs e) =>
popup.IsOpen = false;
}),
PopupViewController.enable_drag_move(_owner, popup));
_children.Add(popup);
_owner.ReleaseMouseCapture();
popup.Closed += on_closed;
FocusManager.SetIsFocusScope(view, true);
Keyboard.Focus(view);
view.Focus();
return popup;
//
void on_closed(object sender, EventArgs e) {
Disposable.dispose(ref hooks);
popup.ReleaseMouseCapture();
if (Mouse.Captured == _owner)
_owner.ReleaseMouseCapture();
popup.Closed -= on_closed;
_children.Remove(popup);
}
async void on_view_preview_mouse_down(object sender, MouseButtonEventArgs e) {
if (WindowStyle.GetUnsafeWindow(popup) is Window win) {
//bool activated = false;
await win.Dispatcher.InvokeAsync(() => {
if (!win.IsActive) {
win.Activate();
//activated = true;
}
});
//if (activated)
popup.BringToFront();
}
}
}
}
}
@@ -55,6 +55,7 @@
<Setter Property="BorderThickness" Value="0"/> <Setter Property="BorderThickness" Value="0"/>
<Setter Property="Focusable" Value="False"/> <Setter Property="Focusable" Value="False"/>
<Setter Property="SelectionMode" Value="Extended"/> <Setter Property="SelectionMode" Value="Extended"/>
<Setter Property="UseLayoutRounding" Value="True"/>
<Setter Property="ColumnHeaderStyle"> <Setter Property="ColumnHeaderStyle">
<Setter.Value> <Setter.Value>
<Style TargetType="GridViewColumnHeader"> <Style TargetType="GridViewColumnHeader">
@@ -26,12 +26,12 @@ namespace mbts.ui.controls {
} }
} }
public class HighPerformanceRow<TRowVM, TColKey> : HighPerformanceRowBase where TRowVM : class, IRowVM { public class HighPerformanceRow<TRowVM> : HighPerformanceRowBase where TRowVM : class, IRowVM {
double _row_height; double _row_height;
ObservableCollection<ColumnBase> _columns; ObservableCollection<ColumnBase> _columns;
List<ColumnGeometry> _column_layout = new List<ColumnGeometry>(); List<ColumnGeometry> _column_layout = new List<ColumnGeometry>();
Dictionary<TColKey, ColumnGeometry> _column_layout_map = new Dictionary<TColKey, ColumnGeometry>(); Dictionary<string, ColumnGeometry> _column_layout_map = new Dictionary<string, ColumnGeometry>();
VisualDictionary<TColKey, FrameworkElement> _element_cells; VisualDictionary<string, FrameworkElement> _element_cells;
RecycleBin<DIYGrid> _grid_backing; RecycleBin<DIYGrid> _grid_backing;
RecycleBin<ListBoxItem> _container_backing; RecycleBin<ListBoxItem> _container_backing;
TRowVM _row; TRowVM _row;
@@ -39,7 +39,7 @@ namespace mbts.ui.controls {
public HighPerformanceRow() : this(DefaultRowHeight) { } public HighPerformanceRow() : this(DefaultRowHeight) { }
public HighPerformanceRow(double row_height) { public HighPerformanceRow(double row_height) {
_row_height = row_height; _row_height = row_height;
_element_cells = new VisualDictionary<TColKey, FrameworkElement>(this); _element_cells = new VisualDictionary<string, FrameworkElement>(this);
_grid_backing = new RecycleBin<DIYGrid>( _grid_backing = new RecycleBin<DIYGrid>(
g => { g.ColumnLayoutChanged += _on_column_layout_changed; g.RowHeightChanged += _on_row_height_changed; }, g => { g.ColumnLayoutChanged += _on_column_layout_changed; g.RowHeightChanged += _on_row_height_changed; },
g => { g.ColumnLayoutChanged -= _on_column_layout_changed; g.RowHeightChanged -= _on_row_height_changed; }); g => { g.ColumnLayoutChanged -= _on_column_layout_changed; g.RowHeightChanged -= _on_row_height_changed; });
@@ -123,7 +123,7 @@ namespace mbts.ui.controls {
protected override Size ArrangeOverride(Size finalSize) { protected override Size ArrangeOverride(Size finalSize) {
foreach (var kv in _column_layout_map) { foreach (var kv in _column_layout_map) {
if (_element_cells.TryGetValue(kv.Key, out FrameworkElement ec)) if (_element_cells.TryGetValue(kv.Key, out FrameworkElement ec))
ec.Arrange(new Rect(new Point(kv.Value.left, 0), new Size(kv.Value.width, _row_height))); ec.Arrange(kv.Value.to_rect(_row_height));
} }
return finalSize; return finalSize;
} }
@@ -148,16 +148,18 @@ namespace mbts.ui.controls {
} }
void _add_columns(IList items) { void _add_columns(IList items) {
foreach (var col in items.OfType<FrameworkElementColumnBase<TColKey>>()) { foreach (ColumnBase col in items) {
var cell_view = col.view_factory(); if (col is IFrameworkElementColumn el_col) {
CellRender.change_position(cell_view, _row_height, _column_layout_map.GetNullable(col.key)); var cell_view = el_col.view_factory();
_element_cells.Add(col.key, cell_view); CellRender.change_position(cell_view, _row_height, _column_layout_map.GetNullable(col.id));
_element_cells.Add(col.id, cell_view);
}
} }
} }
void _remove_columns(IList items) { void _remove_columns(IList items) {
foreach (var col in items.OfType<FrameworkElementColumnBase<TColKey>>()) foreach (ColumnBase col in items)
_element_cells.Remove(col.key); _element_cells.Remove(col.id);
} }
void _on_column_layout_changed(List<ColumnGeometry> column_layout) { void _on_column_layout_changed(List<ColumnGeometry> column_layout) {
@@ -171,10 +173,10 @@ namespace mbts.ui.controls {
} }
void _set_column_layout_map() { void _set_column_layout_map() {
_column_layout_map = new Dictionary<TColKey, ColumnGeometry>(); _column_layout_map = new Dictionary<string, ColumnGeometry>();
foreach (var cg in _column_layout) { foreach (var cg in _column_layout) {
if (cg.column is FrameworkElementColumnBase<TColKey> elc) if (cg.column is IFrameworkElementColumn)
_column_layout_map.Add(elc.key, cg); _column_layout_map.Add(cg.column.id, cg);
} }
} }
#endregion #endregion
@@ -53,11 +53,7 @@ namespace mbts.ui.controls {
if (col.is_partially_obscured) { if (col.is_partially_obscured) {
var obscured_width = col.left - col.unclipped_left; var obscured_width = col.left - col.unclipped_left;
grid.scroll_horizontal(-obscured_width); grid.scroll_horizontal(-obscured_width);
return new ColumnGeometry() { return new ColumnGeometry(col.column, col.super_column, col.left, col.left, col.right);
column = col.column,
left = col.left,
unclipped_left = col.left
};
} }
return col; return col;
} }
@@ -1,6 +1,5 @@
using bts.proto; using bts.proto;
using bts.utils; using bts.utils;
using mbts.ui.controls;
using mbts.ui.converters; using mbts.ui.converters;
using ProtoBuf; using ProtoBuf;
using System; using System;
@@ -24,7 +23,7 @@ namespace mbts.ui.settings {
public static GridSettings Default => public static GridSettings Default =>
new GridSettings( new GridSettings(
selection_highlight: new ColorOpacityProto(FallbackValues.selection_highlight.Color, FallbackValues.selection_highlight.Opacity), selection_highlight: FallbackValues.selection_highlight.rgb_color(),
background: _default_background_color, //new ColorOpacityProto(FallbackValues.background_color.Color, FallbackValues.background_color.Opacity)); background: _default_background_color, //new ColorOpacityProto(FallbackValues.background_color.Color, FallbackValues.background_color.Opacity));
enable_background_color: _default_enable_background_color); enable_background_color: _default_enable_background_color);
@@ -45,11 +44,10 @@ namespace mbts.ui.settings {
public static double font_size => _default_font_size; public static double font_size => _default_font_size;
public static Color font_color => _default_font_color.rgb_color(); public static Color font_color => _default_font_color.rgb_color();
public static FontWeight font_weight => FontWeight.FromOpenTypeWeight(_default_font_weight); public static FontWeight font_weight => FontWeight.FromOpenTypeWeight(_default_font_weight);
public static SolidColorBrush selection_highlight => DIYGrid.DefaultSelectionHighlight; public static Color selection_highlight => Colors.MediumSlateBlue.with(0x63);
public static uint background_color => _default_background; public static uint background_color => _default_background;
} }
public static IValueConverter selection_highlight_converter => ValueConverter.create<GridSettings, SolidColorBrush>(gs => gs.selection_highlight.to_brush().frozen());
public static IValueConverter font_family_converter => ValueConverter.create<GridSettings, FontFamily>(gs => new FontFamily(gs.font_family)); public static IValueConverter font_family_converter => ValueConverter.create<GridSettings, FontFamily>(gs => new FontFamily(gs.font_family));
public static IValueConverter font_weight_converter => ValueConverter.create<GridSettings, FontWeight>(gs => gs.font_weight); public static IValueConverter font_weight_converter => ValueConverter.create<GridSettings, FontWeight>(gs => gs.font_weight);
public static IValueConverter font_size_converter => ValueConverter.create<GridSettings, double>(gs => gs.font_size); public static IValueConverter font_size_converter => ValueConverter.create<GridSettings, double>(gs => gs.font_size);
@@ -71,8 +69,29 @@ namespace mbts.ui.settings {
[DefaultValue(_default_font_color)] [DefaultValue(_default_font_color)]
readonly uint _font_color; readonly uint _font_color;
// selection highlight // selection highlight
ColorOpacityProto _obsolete_selection_highlight_backing;
uint _selection_highlight_backing;
[ProtoMember(5)] [ProtoMember(5)]
readonly ColorOpacityProto _selection_highlight; ColorOpacityProto _obsolete_selection_highlight {
get => _obsolete_selection_highlight_backing;
set {
_obsolete_selection_highlight_backing = value;
// only overwrite non-obsolete selection highlight if it is 0 (assume that means 'unassigned').
if (_selection_highlight_backing == 0) {
var color = value.argb_color;
// ensure reasonable opacity
color.A = MathUtils.within_range(color.A,
GridSettingsMigrationRules.SelectionHighlightIsTranslucent.min_alpha,
GridSettingsMigrationRules.SelectionHighlightIsTranslucent.max_alpha);
_selection_highlight_backing = color.rgb_color();
}
}
}
[ProtoMember(10)]
uint _selection_highlight {
get => _selection_highlight_backing;
set => _selection_highlight_backing = value;
}
// columns // columns
[ProtoMember(6)] [ProtoMember(6)]
List<GridColumnSettings> _columns; List<GridColumnSettings> _columns;
@@ -101,7 +120,7 @@ namespace mbts.ui.settings {
double font_size = _default_font_size, double font_size = _default_font_size,
FontWeight font_weight = default, FontWeight font_weight = default,
uint font_color = _default_font_color, uint font_color = _default_font_color,
ColorOpacityProto? selection_highlight = null, uint selection_highlight = 0,
IEnumerable<GridColumnSettings> columns = null, IEnumerable<GridColumnSettings> columns = null,
IEnumerable<SortingCriteria> sorting_criterion = null, IEnumerable<SortingCriteria> sorting_criterion = null,
uint background = _default_background, uint background = _default_background,
@@ -111,7 +130,7 @@ namespace mbts.ui.settings {
_font_size = font_size; _font_size = font_size;
_font_color = font_color; _font_color = font_color;
_font_weight = (ushort)font_weight.ToOpenTypeWeight(); _font_weight = (ushort)font_weight.ToOpenTypeWeight();
_selection_highlight = selection_highlight ?? new ColorOpacityProto(0, 1); _selection_highlight = selection_highlight;
_columns = new List<GridColumnSettings>(columns.empty_if_null()); _columns = new List<GridColumnSettings>(columns.empty_if_null());
_sorting_criterion = new List<SortingCriteria>(sorting_criterion.empty_if_null()); _sorting_criterion = new List<SortingCriteria>(sorting_criterion.empty_if_null());
_background = background; _background = background;
@@ -123,29 +142,27 @@ namespace mbts.ui.settings {
public uint font_color => _font_color; public uint font_color => _font_color;
public FontWeight font_weight => FontWeight.FromOpenTypeWeight(_font_weight); public FontWeight font_weight => FontWeight.FromOpenTypeWeight(_font_weight);
public Color background => _background.argb_color(); public Color background => _background.argb_color();
public ColorOpacityProto selection_highlight => _selection_highlight; public Color selection_highlight => _selection_highlight.argb_color();
public uint background_color => _background; public uint background_color => _background;
public bool enable_background_color => _enable_background_color; public bool enable_background_color => _enable_background_color;
public IReadOnlyList<GridColumnSettings> columns => _columns ?? (_columns = new List<GridColumnSettings>(0)); public IReadOnlyList<GridColumnSettings> columns => _columns ?? (_columns = new List<GridColumnSettings>(0));
[Obsolete] // TODO: remove sorting_criterion from GridSettings entirely. This should be part of IShellWindow's StartupData, since it is an instance-specific setting, and prob not part of the shared defaults [Obsolete] // TODO: remove sorting_criterion from GridSettings entirely. This should be part of IShellWindow's StartupData, since it is an instance-specific setting, and prob not part of the shared defaults
public IReadOnlyList<SortingCriteria> sorting_criterion => _sorting_criterion ?? (_sorting_criterion = new List<SortingCriteria>(0)); public IReadOnlyList<SortingCriteria> sorting_criterion => _sorting_criterion ?? (_sorting_criterion = new List<SortingCriteria>(0));
public static GridSettings get_default() =>
new GridSettings(_default_font_family, _default_font_size, FontWeights.Normal, _default_font_color, new ColorOpacityProto(Colors.MediumSlateBlue, 0.4));
public GridSettings with( public GridSettings with(
IEnumerable<GridColumnSettings> columns = null, IEnumerable<GridColumnSettings> columns = null,
IEnumerable<SortingCriteria> sorting_criterion = null, IEnumerable<SortingCriteria> sorting_criterion = null,
string font_family = null, string font_family = null,
double font_size = double.NaN, double font_size = double.NaN,
uint? background = null, uint? background = null,
bool? enable_background_color = null) => bool? enable_background_color = null,
uint? selection_highlight = null) =>
new GridSettings( new GridSettings(
font_family ?? _font_family, font_family ?? _font_family,
DoubleHelper.IsNaNOrInfinityOr(font_size, 0) ? _font_size : font_size, DoubleHelper.IsNaNOrInfinityOr(font_size, 0) ? _font_size : font_size,
font_weight, font_weight,
_font_color, _font_color,
_selection_highlight, selection_highlight ?? _selection_highlight,
columns ?? _columns, columns ?? _columns,
sorting_criterion ?? _sorting_criterion, sorting_criterion ?? _sorting_criterion,
background ?? _background, background ?? _background,
@@ -1,4 +1,6 @@
using bts.collections; using bts.collections;
using bts.settings;
using bts.utils;
using mbts.ui.controls; using mbts.ui.controls;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -45,6 +47,19 @@ namespace mbts.ui.settings {
return false; return false;
} }
public static GridSettings hide_cols<T>(GridSettings grid, IEnumerable<T> columns) where T : struct =>
grid.with(hide_cols(grid.columns, columns.Select(c => c.ToString())));
public static GridSettings hide_cols(GridSettings grid, IEnumerable<string> columns) =>
grid.with(hide_cols(grid.columns, columns));
public static IEnumerable<GridColumnSettings> hide_cols(IEnumerable<GridColumnSettings> cols, IEnumerable<string> columns) {
// hide columns who's data is implied by the grouping
var col_hash = new HashSet<string>(columns);
foreach (var c in cols)
yield return col_hash.Contains(c.id) ? c.with(is_visible: false) : c;
}
public static TColKey? parse_col_id<TColKey>(string id) where TColKey : struct => public static TColKey? parse_col_id<TColKey>(string id) where TColKey : struct =>
Enum.TryParse(id, true, out TColKey key) ? key : (TColKey?)null; Enum.TryParse(id, true, out TColKey key) ? key : (TColKey?)null;
@@ -116,4 +131,26 @@ namespace mbts.ui.settings {
return false; return false;
} }
} }
static class GridSettingsMigrationRules {
public class SelectionHighlightIsTranslucent : ISettingsMigrationRule<GridSettings> {
public const byte min_alpha = 30, max_alpha = 200;
public static bool apply(GridSettings settings, out GridSettings new_settings) {
if (settings != null) {
var sl = settings.selection_highlight;
var a = MathUtils.within_range(sl.A, (byte)30, (byte)200);
if (sl.A != a) {
sl.A = a;
new_settings = settings.with(selection_highlight: sl.rgb_color());
return true;
}
}
new_settings = null;
return false;
}
bool ISettingsMigrationRule<GridSettings>.apply(GridSettings settings, out GridSettings new_settings) =>
apply(settings, out new_settings);
}
}
} }
@@ -30,7 +30,8 @@ namespace mbts.ui {
readonly DelegateProperty<FontFamily> _font_family; readonly DelegateProperty<FontFamily> _font_family;
readonly DelegateProperty<FontWeight> _font_weight; readonly DelegateProperty<FontWeight> _font_weight;
readonly DelegateProperty<double> _font_size; readonly DelegateProperty<double> _font_size;
readonly DelegateProperty<SolidColorBrush> _font_color, _selection_highlight, _background_color; readonly DelegateProperty<SolidColorBrush> _font_color, _background_color;
readonly DelegateProperty<Color> _selection_highlight;
readonly SetMap<IPredicate<TRowData>, AnimationDefinitionWrapper<TRow>> _animation_defs = new SetMap<IPredicate<TRowData>, AnimationDefinitionWrapper<TRow>>(); readonly SetMap<IPredicate<TRowData>, AnimationDefinitionWrapper<TRow>> _animation_defs = new SetMap<IPredicate<TRowData>, AnimationDefinitionWrapper<TRow>>();
readonly Func<TPredicateData> _predicate_data_factory; readonly Func<TPredicateData> _predicate_data_factory;
readonly Func<TPredicateData, IPredicate<TRowData>> _predicate_factory; readonly Func<TPredicateData, IPredicate<TRowData>> _predicate_factory;
@@ -76,7 +77,7 @@ namespace mbts.ui {
_font_weight = backing(nameof(font_weight), () => grid_settings.font_weight, nameof(grid_settings)); _font_weight = backing(nameof(font_weight), () => grid_settings.font_weight, nameof(grid_settings));
_font_size = backing(nameof(font_size), () => grid_settings.font_size, nameof(font_size)); _font_size = backing(nameof(font_size), () => grid_settings.font_size, nameof(font_size));
_font_color = backing(nameof(font_color), () => grid_settings.font_color.rgb_solid_brush().frozen(), nameof(grid_settings)); _font_color = backing(nameof(font_color), () => grid_settings.font_color.rgb_solid_brush().frozen(), nameof(grid_settings));
_selection_highlight = backing(nameof(selection_highlight), () => grid_settings.selection_highlight.to_brush().frozen(), nameof(grid_settings)); _selection_highlight = backing(nameof(selection_highlight), () => grid_settings.selection_highlight, nameof(grid_settings));
_background_color = backing(nameof(background_color), () => grid_settings.background_color.argb_color().to_solid_brush().frozen(), nameof(grid_settings)); _background_color = backing(nameof(background_color), () => grid_settings.background_color.argb_color().to_solid_brush().frozen(), nameof(grid_settings));
} }
@@ -88,7 +89,7 @@ namespace mbts.ui {
public FontWeight font_weight => _font_weight.Value; public FontWeight font_weight => _font_weight.Value;
public double font_size => _font_size.Value; public double font_size => _font_size.Value;
public SolidColorBrush font_color => _font_color.Value; public SolidColorBrush font_color => _font_color.Value;
public SolidColorBrush selection_highlight => _selection_highlight.Value; public Color selection_highlight => _selection_highlight.Value;
public SolidColorBrush background_color => _background_color.Value; public SolidColorBrush background_color => _background_color.Value;
public GridSettingsVM<TRowData, TPredicateData, TSettingsData> create_vm(GridSettings settings) { public GridSettingsVM<TRowData, TPredicateData, TSettingsData> create_vm(GridSettings settings) {
@@ -134,8 +134,16 @@ namespace mbts.spark {
foreach (IGrouping<TPredicateData, CellAnimation> g in animations) foreach (IGrouping<TPredicateData, CellAnimation> g in animations)
animation_map.AddOrUpdate(g.Key, p => animation_tuple(c: g), (p, t) => t.cell_animations.AddRange(g)); animation_map.AddOrUpdate(g.Key, p => animation_tuple(c: g), (p, t) => t.cell_animations.AddRange(g));
} }
return _create_settings_obj(new GridSettings(font_family.name(), font_size, font_weight, font_color.color.rgb_color(), selection_highlight.to_proto(), col_settings, var gs = new GridSettings(
background: background_color.color.with((byte)(MathUtils.within_range(0, 1, background_color.opacity) * 255.0)).rgb_color()), font_family.name(),
font_size,
font_weight,
font_color.color.rgb_color(),
selection_highlight.color.rgb_color(),
col_settings);
if (show_background_color)
gs = gs.with(background: background_color.color.rgb_color());
return _create_settings_obj(gs,
animation_map.Select(kv => PredicateAnimations.create_data<TRowData, TPredicateData>(kv.Key, kv.Value.cell_animations, kv.Value.row_animations, kv.Value.sounds))); animation_map.Select(kv => PredicateAnimations.create_data<TRowData, TPredicateData>(kv.Key, kv.Value.cell_animations, kv.Value.row_animations, kv.Value.sounds)));
// //
(List<RowAnimation> row_animations, List<SoundNotification> sounds, List<CellAnimation> cell_animations) animation_tuple(IEnumerable<RowAnimation> r = null, IEnumerable<SoundNotification> s = null, IGrouping<TPredicateData, CellAnimation> c = null) => (List<RowAnimation> row_animations, List<SoundNotification> sounds, List<CellAnimation> cell_animations) animation_tuple(IEnumerable<RowAnimation> r = null, IEnumerable<SoundNotification> s = null, IGrouping<TPredicateData, CellAnimation> c = null) =>
@@ -146,7 +154,7 @@ namespace mbts.spark {
_font_family.set(new FontFamily(sd.general.font_family)); _font_family.set(new FontFamily(sd.general.font_family));
_font_weight.set(sd.general.font_weight); _font_weight.set(sd.general.font_weight);
font_color.load_from(sd.general.font_color.rgb_solid_brush()); font_color.load_from(sd.general.font_color.rgb_solid_brush());
selection_highlight.load_from(sd.general.selection_highlight.to_brush()); selection_highlight.color = sd.general.selection_highlight;
_show_background_color.set(sd.general.enable_background_color); _show_background_color.set(sd.general.enable_background_color);
if (sd.general.enable_background_color) { if (sd.general.enable_background_color) {
// note that when the OB is moved to allow background colors // note that when the OB is moved to allow background colors
@@ -20,7 +20,8 @@ namespace mbts.ui {
readonly DelegateProperty<FontFamily> _font_family; readonly DelegateProperty<FontFamily> _font_family;
readonly DelegateProperty<FontWeight> _font_weight; readonly DelegateProperty<FontWeight> _font_weight;
readonly DelegateProperty<double> _font_size; readonly DelegateProperty<double> _font_size;
readonly DelegateProperty<SolidColorBrush> _font_color, _selection_highlight, _background_color; readonly DelegateProperty<SolidColorBrush> _font_color, _background_color;
readonly DelegateProperty<Color> _selection_highlight;
readonly IReadOnlyDictionary<string, ImmutableColumnSettingStore> _column_flags; readonly IReadOnlyDictionary<string, ImmutableColumnSettingStore> _column_flags;
public SimpleGridSettingsManager(ObservableCollection<ColumnBase> columns) public SimpleGridSettingsManager(ObservableCollection<ColumnBase> columns)
@@ -34,7 +35,7 @@ namespace mbts.ui {
_font_weight = backing(nameof(font_weight), () => grid_settings.font_weight, nameof(grid_settings)); _font_weight = backing(nameof(font_weight), () => grid_settings.font_weight, nameof(grid_settings));
_font_size = backing(nameof(font_size), () => grid_settings.font_size, nameof(font_size)); _font_size = backing(nameof(font_size), () => grid_settings.font_size, nameof(font_size));
_font_color = backing(nameof(font_color), () => grid_settings.font_color.rgb_solid_brush().frozen(), nameof(grid_settings)); _font_color = backing(nameof(font_color), () => grid_settings.font_color.rgb_solid_brush().frozen(), nameof(grid_settings));
_selection_highlight = backing(nameof(selection_highlight), () => grid_settings.selection_highlight.to_brush().frozen(), nameof(grid_settings)); _selection_highlight = backing(nameof(selection_highlight), () => grid_settings.selection_highlight, nameof(grid_settings));
_background_color = backing(nameof(background_color), () => grid_settings.background_color.argb_color().to_solid_brush().frozen(), nameof(grid_settings)); _background_color = backing(nameof(background_color), () => grid_settings.background_color.argb_color().to_solid_brush().frozen(), nameof(grid_settings));
_row_vms = row_vms; _row_vms = row_vms;
} }
@@ -44,8 +45,8 @@ namespace mbts.ui {
public FontWeight font_weight => _font_weight.Value; public FontWeight font_weight => _font_weight.Value;
public double font_size => _font_size.Value; public double font_size => _font_size.Value;
public SolidColorBrush font_color => _font_color.Value; public SolidColorBrush font_color => _font_color.Value;
public SolidColorBrush selection_highlight => _selection_highlight.Value;
public SolidColorBrush background_color => _background_color.Value; public SolidColorBrush background_color => _background_color.Value;
public Color selection_highlight => _selection_highlight.Value;
public SimpleGridSettingsVM create_vm(GridSettings settings) { public SimpleGridSettingsVM create_vm(GridSettings settings) {
var vm = new SimpleGridSettingsVM(_column_flags.ToDictionary(kv => kv.Key, kv => kv.Value.flags)); var vm = new SimpleGridSettingsVM(_column_flags.ToDictionary(kv => kv.Key, kv => kv.Value.flags));
@@ -120,7 +120,7 @@ namespace mbts.spark {
font_size, font_size,
font_weight, font_weight,
font_color.color.rgb_color(), font_color.color.rgb_color(),
selection_highlight.to_proto(), selection_highlight.color.rgb_color(),
columns.Select(c => c.create())); columns.Select(c => c.create()));
if (show_background_color) if (show_background_color)
rv = rv.with(background: background_color.color.rgb_color()); rv = rv.with(background: background_color.color.rgb_color());
@@ -134,7 +134,7 @@ namespace mbts.spark {
_font_family.set(new FontFamily(value.font_family)); _font_family.set(new FontFamily(value.font_family));
_font_weight.set(value.font_weight); _font_weight.set(value.font_weight);
font_color.load_from(value.font_color.rgb_solid_brush()); font_color.load_from(value.font_color.rgb_solid_brush());
selection_highlight.color = value.selection_highlight.argb_color; selection_highlight.color = value.selection_highlight;
_show_background_color.set(value.enable_background_color); _show_background_color.set(value.enable_background_color);
if (value.enable_background_color) { if (value.enable_background_color) {
background_color.color = value.background; background_color.color = value.background;
@@ -0,0 +1,144 @@
<ResourceDictionary
x:Class="mbts.ui.spark.OrderTicketResources"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:msys="clr-namespace:bts.api;assembly=spark_api"
xmlns:sp="clr-namespace:mbts.spark"
xmlns:u="clr-namespace:mbts.ui"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/Buttons.xaml"/>
<ResourceDictionary Source="/view/Resources/Converters.xaml"/>
</ResourceDictionary.MergedDictionaries>
<sys:Double x:Key="HorizontalSpacing">8.0</sys:Double>
<sys:Double x:Key="VerticalSpacing">4.0</sys:Double>
<sys:Double x:Key="ButtonHeight">22.0</sys:Double>
<Style x:Key="SellButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="{u:BTSColor MarketData.ask}"/>
<Setter Property="BorderBrush" Value="{u:BTSColor UI.Button.normal_border}"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="MinHeight" Value="40"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="Content">
<Setter.Value>
<TextBlock VerticalAlignment="Center" Foreground="{u:BTSColor UI.alternate_text}">Sell</TextBlock>
</Setter.Value>
</Setter>
<Setter Property="Template" Value="{StaticResource SellButtonTemplate}"/>
</Style>
<Style x:Key="BuyButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="{u:BTSColor MarketData.bid}"/>
<Setter Property="BorderBrush" Value="{u:BTSColor UI.Button.normal_border}"/>
<Setter Property="Padding" Value="2"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="MinHeight" Value="40"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="Content">
<Setter.Value>
<TextBlock VerticalAlignment="Center" Foreground="{u:BTSColor UI.alternate_text}">Buy</TextBlock>
</Setter.Value>
</Setter>
<Setter Property="Template" Value="{StaticResource BuyButtonTemplate}"/>
</Style>
<DataTemplate DataType="{x:Type sp:BBOVM}">
<TextBlock Margin="2">
<TextBlock.Inlines>
<Run Text="{Binding security, Mode=OneWay}" FontWeight="Bold"/>
<Run Foreground="{u:BTSColor MarketData.bid}" FontSize="10" Text="{Binding bid_size, Mode=OneWay, StringFormat='{}({0})'}"/>
<Run Foreground="{u:BTSColor MarketData.bid}" FontWeight="Bold">
<Run.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="bid"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</Run.Text>
</Run>
<Run Foreground="{u:BTSColor MarketData.ask}" FontWeight="Bold">
<Run.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="ask"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</Run.Text>
</Run>
<Run Foreground="{u:BTSColor MarketData.ask}" FontSize="10" Text="{Binding ask_size, Mode=OneWay, StringFormat='{}({0})'}"/>
</TextBlock.Inlines>
</TextBlock>
</DataTemplate>
<DataTemplate DataType="{x:Type sp:NewOrderTicketVM}">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalSpacing}}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="120"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSpacing}}" MaxWidth="{Binding Source={StaticResource HorizontalSpacing}}"/>
<ColumnDefinition MinWidth="120"/>
</Grid.ColumnDefinitions>
<usp:OrderModificationControl Grid.ColumnSpan="3"/>
<Button Grid.Row="2" Style="{StaticResource BuyButton}" Command="{Binding send_order}" CommandParameter="{u:Enum Buy, Type=msys:Side}"/>
<Button Grid.Row="2" Grid.Column="2" Style="{StaticResource SellButton}" Command="{Binding send_order}" CommandParameter="{u:Enum Sell, Type=msys:Side}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type sp:ExistingOrderTicketVM}">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalSpacing}}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="120"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSpacing}}"/>
<ColumnDefinition MinWidth="120"/>
</Grid.ColumnDefinitions>
<usp:OrderModificationControl Grid.ColumnSpan="3"/>
<Button
Grid.Row="2"
Command="{Binding modify_order}"
IsDefault="True"
MinHeight="40"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock HorizontalAlignment="Center" FontWeight="Bold">OK</TextBlock>
<TextBlock
Grid.Row="1" HorizontalAlignment="Center" Margin="0,2,0,0" FontSize="9" Text="{Binding dirty_items_text}"
Visibility="{Binding dirty_items_text, Converter={StaticResource DirtyItemsVisibilityConverter}}"
/>
</Grid>
</Button>
<Button
Grid.Row="2"
Grid.Column="2"
Command="ApplicationCommands.Close"
FontWeight="Bold"
IsCancel="True"
MinHeight="40"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
>
Cancel
</Button>
</Grid>
</DataTemplate>
</ResourceDictionary>
@@ -0,0 +1,10 @@
using mbts.ui.utility;
using System.Windows;
namespace mbts.ui.spark {
partial class OrderTicketResources : ResourceDictionary {
public OrderTicketResources() {
InitializeComponent();
}
}
}
@@ -1,8 +1,10 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" <ResourceDictionary
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:c="clr-namespace:mbts.ui.controls" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:usp="clr-namespace:mbts.ui.spark" xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:uspcv="clr-namespace:mbts.ui.spark.converters"> xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:uspcv="clr-namespace:mbts.ui.spark.converters"
>
<uspcv:OrderTypeBrushConverter x:Key="OrderTypeBrushConverter"/> <uspcv:OrderTypeBrushConverter x:Key="OrderTypeBrushConverter"/>
<uspcv:OrderTypeDisplayTextConverter x:Key="OrderTypeDisplayTextConverter"/> <uspcv:OrderTypeDisplayTextConverter x:Key="OrderTypeDisplayTextConverter"/>
<Style TargetType="usp:OrderTypeItem"> <Style TargetType="usp:OrderTypeItem">
@@ -26,15 +28,17 @@
<ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/>
<ColumnDefinition/> <ColumnDefinition/>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<c:Badge <Rectangle
HorizontalAlignment="Left" HorizontalAlignment="Left"
VerticalAlignment="Center" VerticalAlignment="Center"
Background="{Binding BadgeFill, RelativeSource={RelativeSource TemplatedParent}}" Fill="{Binding BadgeFill, RelativeSource={RelativeSource TemplatedParent}}"
BorderThickness="1" Stroke="Black"
StrokeThickness="1"
Width="15" Width="15"
Height="10" Height="10"
Focusable="False" Focusable="False"
IsTabStop="False" RadiusX="{x:Static c:Badge.DefaultCornerRadius}"
RadiusY="{x:Static c:Badge.DefaultCornerRadius}"
/> />
<TextBlock <TextBlock
x:Name="text" x:Name="text"
@@ -0,0 +1,133 @@
<ResourceDictionary
x:Class="mbts.ui.spark.AuxiliaryDataResources"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:sp="clr-namespace:mbts.spark"
>
<!--Fills-->
<DataTemplate DataType="{x:Type sp:FillsVM}">
<usp:FillsView/>
</DataTemplate>
<!--OrderBook-->
<DataTemplate DataType="{x:Type sp:OrderBookVM}">
<sp:MiniOrderBookView/>
</DataTemplate>
<!--Header (Title Bar)-->
<DataTemplate DataType="{x:Type usp:AuxiliaryDataHeader}">
<Grid MaxWidth="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=ContentPresenter}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!--
Please listen to my angry rant...this is seriously what it takes to auto fit text into a dynamically sized parent container:
1) A hidden textblock, which will be allowed to grow freely, so it's ActualWidth represents the 'desired width.'
- don't forget to add a pixel of padding, because setting the MaxWidth to the ActualWidth of a perfectly
measured TextBlock with the same Text/Typeface may still trigger the TextTrimming ellipsis.
2) A canvas (with 0 width) to wrap the hidden textblock, so that its width does not affect that of the parent.
3) A ridiculously long MultiBinding, that has child bindings to the ActualWidth of each sibling visual element,
which are summed by the Converter to yield the total occupied width.
4) Finally: a visible textblock, with a MaxWidth bound to the minimum of the 'desired width' and the 'available width - occupied width.'
5) A new computer, to replace the one that was defenestrated after the frustratingly long journey to this solution.
-->
<Canvas>
<TextBlock x:Name="PART_ContextHidden" FontWeight="Bold" Padding="1,0,0,0" Text="{Binding context}" Visibility="Hidden"/>
</Canvas>
<TextBlock
x:Name="PART_Context"
FontWeight="Bold"
HorizontalAlignment="Left"
Margin="4,0,0,0"
Text="{Binding context}"
TextTrimming="CharacterEllipsis"
VerticalAlignment="Center"
>
<TextBlock.Tag>
<MultiBinding>
<MultiBinding.Converter>
<cv:DoubleDynamicSubtractionConverter Minimum="0"/>
</MultiBinding.Converter>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource AncestorType=ContentPresenter}"/>
<Binding Path="ActualWidth" ElementName="PART_KeepOpen"/>
<Binding Path="ActualWidth" ElementName="PART_Close"/>
<Binding Path="ActualWidth" ElementName="PART_Title"/>
<Binding Source="{u:Double 20}"/>
</MultiBinding>
</TextBlock.Tag>
<TextBlock.MaxWidth>
<MultiBinding Converter="{x:Static cv:MinimumConverter.Instance}">
<Binding Path="ActualWidth" ElementName="PART_ContextHidden"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>
</MultiBinding>
</TextBlock.MaxWidth>
</TextBlock>
<TextBlock
x:Name="PART_Title"
Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="4,0,0,0"
FontWeight="Bold"
Text="{Binding title}"
ToolTip="{Binding title}"
>
<TextBlock.Foreground>
<SolidColorBrush Color="{Binding title_foreground}"/>
</TextBlock.Foreground>
</TextBlock>
<CheckBox x:Name="PART_KeepOpen" Grid.Column="2" VerticalAlignment="Center" Margin="4,0,0,0" Focusable="False" IsChecked="{Binding StaysOpen, RelativeSource={RelativeSource AncestorType=Popup}}">Keep Open</CheckBox>
<Button x:Name="PART_Close" Grid.Column="3" HorizontalAlignment="Right" Margin="4" Command="{x:Static ApplicationCommands.Close}" CommandTarget="{Binding RelativeSource={RelativeSource AncestorType=HeaderedContentControl}}" Style="{StaticResource RoundCloseButton}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type usp:OrderTicketHeader}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentControl Content="{Binding bbo}"/>
<CheckBox Grid.Column="2" VerticalAlignment="Center" Margin="4,0,0,0" Focusable="False" IsChecked="{Binding StaysOpen, RelativeSource={RelativeSource AncestorType=Popup}}">Keep Open</CheckBox>
<Button Grid.Column="3" HorizontalAlignment="Right" Margin="4" Command="{x:Static ApplicationCommands.Close}" CommandTarget="{Binding RelativeSource={RelativeSource AncestorType=HeaderedContentControl}}" Style="{StaticResource RoundCloseButton}"/>
</Grid>
</DataTemplate>
<ControlTemplate x:Key="PopupChildTemplate" TargetType="HeaderedContentControl">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ContentPresenter ContentSource="Header" Width="{Binding ActualWidth, ElementName=Content}"/>
<ContentPresenter
x:Name="Content"
Grid.Row="1"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
/>
</Grid>
</Border>
</ControlTemplate>
<Style x:Key="PopupChildStyleKey" TargetType="HeaderedContentControl">
<Setter Property="Background" Value="{DynamicResource CommonBackground}"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="MaxHeight" Value="300"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="Template" Value="{StaticResource PopupChildTemplate}"/>
</Style>
</ResourceDictionary>
@@ -0,0 +1,36 @@
using mbts.spark;
using mbts.ui.shell;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace mbts.ui.spark {
partial class AuxiliaryDataResources : ResourceDictionary {
public AuxiliaryDataResources() =>
InitializeComponent();
public static string PopupChildStyleKey => nameof(PopupChildStyleKey);
}
class AuxiliaryDataHeader : ViewModelBase {
string
_title,
_context;
Color _title_foreground;
bool _keep_open;
public Color title_foreground { get => _title_foreground; set => Set(ref _title_foreground, value); }
public string title { get => _title; set => Set(ref _title, value); }
public string context { get => _context; set => Set(ref _context, value); }
public bool keep_open { get => _keep_open; set => Set(ref _keep_open, value); }
}
class OrderTicketHeader : ViewModelBase {
bool _keep_open;
public BBOVM bbo { get; set; }
public bool keep_open { get => _keep_open; set => Set(ref _keep_open, value); }
}
class ConstrainedTextBlock : TextBlock {
}
}
@@ -1,9 +1,30 @@
using System; using mbts.ui.dpi;
using System;
using System.Windows;
using System.Windows.Controls.Primitives; using System.Windows.Controls.Primitives;
using System.Windows.Input; using System.Windows.Input;
namespace mbts.ui.controls { namespace mbts.ui.controls {
static class PopupViewController { static class PopupViewController {
#region ButtonSource
public static readonly DependencyProperty ButtonSourceProperty =
DependencyProperty.RegisterAttached("ButtonSource", typeof(ButtonBase), typeof(PopupViewController),
new PropertyMetadata(OnButtonSourceChanged));
static void OnButtonSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (d is Popup popup)
popup.SetValue(ButtonSourceDependencyPropertyKey,
e.NewValue is ButtonBase button ? attach(popup, button) : null);
}
public static bool GetButtonSource(DependencyObject d) => (bool)d.GetValue(ButtonSourceProperty);
public static void SetButtonSource(DependencyObject d, bool value) => d.SetValue(ButtonSourceProperty, value);
static readonly DependencyPropertyKey ButtonSourceDependencyPropertyKey =
DependencyProperty.RegisterAttachedReadOnly("ButtonSourceDependency", typeof(IDisposable), typeof(PopupViewController),
new PropertyMetadata(FrameworkElementLifeDependencyHelper.DisposeOld));
#endregion
public static IDisposable attach(Popup popup, ButtonBase open_cmd_source, bool auto_focus_popup_root_on_open = false) { public static IDisposable attach(Popup popup, ButtonBase open_cmd_source, bool auto_focus_popup_root_on_open = false) {
/// There is a paradoxical corner case handled here that occurs when the user clicks the button to 'close' the popup. /// There is a paradoxical corner case handled here that occurs when the user clicks the button to 'close' the popup.
/// Conventional logic might dictate that a <see cref="ToggleButton "/> be used to bind <see cref="ToggleButton.IsChecked"/> to <see cref="Popup.IsOpen"/>, /// Conventional logic might dictate that a <see cref="ToggleButton "/> be used to bind <see cref="ToggleButton.IsChecked"/> to <see cref="Popup.IsOpen"/>,
@@ -34,5 +55,54 @@ namespace mbts.ui.controls {
ignore_open_cmd = true; ignore_open_cmd = true;
} }
} }
/// <summary>
/// Enables drag move behavior by incrementing the popoup's <see cref="Popup.HorizontalOffset"/> and <see cref="Popup.VerticalOffset"/> properties
/// according to the mouse drag delta.
/// </summary>
/// <param name="surface">The element to initiate drag ops.</param>
/// <param name="popup">The popup to exhibit drag move behavior.</param>
/// <param name="adjust_to_actual_offset">
/// Whether or not the drag delta should be calculated by the popup's position actual position on the screen, or the popup's offset values
/// (the latter are not neccesarily within the bounds of the screen).
/// </param>
/// <returns>An <see cref="IDisposable"/> that will disable the drag behavior when disposed.</returns>
public static IDisposable enable_drag_move(FrameworkElement surface, Popup popup, bool adjust_to_actual_offset = true) {
var child = popup.Child;
Point offset = get_offset();
Point? last_drag_pt = null;
return DragDropHelper.subscribe_drag_coordinates(surface, popup.Child as FrameworkElement).Subscribe(drag_pt => {
child = popup.Child;
offset = get_offset();
if (drag_pt.HasValue) {
if (last_drag_pt.HasValue) {
(popup.HorizontalOffset, popup.VerticalOffset) =
offset.plus(drag_pt.Value.minus(last_drag_pt.Value)).deconstruct();
} else {
popup.SetCurrentValue(Popup.StaysOpenProperty, true);
Mouse.Capture(surface);
}
} else {
if (popup.StaysOpen) {
// popup.Child must be focused BEFORE the StaysOpen binding target (i.e., the popup itself) is updated;
// Otherwise, if StaysOpen becomes false as a result of the update,
// the popup would close in response to the 'LostFocus' event generated by the late Child.Focus call.
// A reasonable person may ask, "Well why must the Popup.Child be focused at all?"
// The answer is that the popup must be focused, to automatically close when it loses focus.
popup.Child.Focus();
surface.ReleaseMouseCapture();
popup.GetBindingExpression(Popup.StaysOpenProperty)?.UpdateTarget();
} else {
surface.ReleaseMouseCapture();
}
}
last_drag_pt = drag_pt;
});
Point get_offset() =>
adjust_to_actual_offset ?
(child == null ? default : child.PointToScreenPixels(default)) :
new Point(popup.HorizontalOffset, popup.VerticalOffset);
}
} }
} }
@@ -0,0 +1,232 @@
using bts;
using mbts.ui.native;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using System.Windows.Threading;
namespace mbts.ui.controls {
/// <summary>
/// A <see cref="Popup"/> that can change parent windows (according to the <see cref="WindowStyle.UnsafeWindowProperty"/>).
/// Also unlike normal popups, it vanishes when its parent window is minimized, and reappears when it is restored/maximized.
/// </summary>
class ZPopup : Popup {
static int _id_counter;
static ZPopup _topmost_zpopup;
readonly LoggerContext _log;
IDisposable _window_sub;
Window _window;
bool _is_parent_changing;
public ZPopup() {
_log = new LoggerContext(Log.Ui, $"ZPop {ID} - ", null);
SetCurrentValue(IDProperty, Interlocked.Increment(ref _id_counter));
WindowStyle.AddUnsafeWindowChangedHandler(this, _on_unsafe_window_changed);
}
// The ID property helped diagnose issues during developement, by making it easy to keep track of popup instances
// (the heavy logging in this class provides additional diagnostic aid).
// As window activation/focus issues are nearly impossible to debug in the traditional debugger;
// (the active window (and focus) changes to the debugger window when break points are hit),
// such aids have proven quite useful.
#region ID
public static readonly DependencyProperty IDProperty =
WPFHelper.create_dp<int, ZPopup>(nameof(ID));
public int ID {
get { return (int)GetValue(IDProperty); }
set { SetValue(IDProperty, value); }
}
#endregion
public void BringToFront() {
/// The logic below assumes that there will only be a single generation of <see cref="ZPopup"/>s
/// (i.e., that there won't be any <see cref="ZPopup"/>s nested inside of another <see cref="ZPopup"/>).
/// Don't reset the popup's position if it is already topmost wrt the other <see cref="ZPopup"/>s;
/// this prevents this popup from covering an open child <see cref="Popup"/>, as it would become the topmost of all windows.
if (Interlocked.Exchange(ref _topmost_zpopup, this) != this) {
// Reset the unsafe window hooks, so the callbacks are moved to the back of the invocation list.
// As each popup window is assigned the 'TopMost' z position in the parent window 'Activated' callback, and 'NoTopMost' in the 'Deactivated' callback,
// the relative z positions of sibling popups (i.e., w/ a common parent window) are a reverse linear translation of the invocation list (a LIFO/Stack arrangment).
WindowStyle.RemoveUnsafeWindowChangedHandler(this, _on_unsafe_window_changed);
WindowStyle.AddUnsafeWindowChangedHandler(this, _on_unsafe_window_changed);
_on_window(_window, false);
}
}
protected override void OnClosed(EventArgs e) {
_log.info($"disposing parent window sub - reason: {(_is_parent_changing ? "parent change" : "closed")}.");
Disposable.dispose(ref _window_sub);
// base.OnClose invokes the Closed event - don't do that if parent is changing.
// Reason: when the parent changes, the popup must be closed then reopened to detach from the old presentation source.
// Popups are quite the pain in the ass, lemme tell ya! (it might even be worth it to do a custom implementation, rather than derive from msoft's Popup).
if (!_is_parent_changing)
base.OnClosed(e);
}
protected override void OnOpened(EventArgs e) {
// Links that explain the nuances of SetWindowPos:
// https://www.pinvoke.net/default.aspx/user32.setwindowpos
// https://devblogs.microsoft.com/oldnewthing/20051121-10/?p=33263
// Links to the Popup base class code that calls SetWindowPos:
// https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/Primitives/Popup.cs,4fabcf08378ac9be,references
// https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/Primitives/Popup.cs,fef52e73f7d51076
// https://referencesource.microsoft.com/#WindowsBase/Shared/MS/Win32/UnsafeNativeMethodsCLR.cs,d9c926e7b8eb6e2c
/// The main purpose of this class is to maintain the popup window's Z index so that it is always just above the main/parent window (and beneath every other window on top of it);
/// in other words, this should always be the case: popup_win.ZIndex == parent_win.ZIndex + 1.
/// Brief notes on window z order, which can be manipulated via <see cref="native.NativeMethods.SetWindowPos(IntPtr, IntPtr, int, int, int, int, SWP)"/>:
/// - There are 2 'z order' groups of windows
/// 1) 'Normal' windows: windows displayed via <see cref="Window.Show"/> (including the shell windows in BTS), and non-modal dialogs
/// 2) 'TopMost' windows: modal dialogs, and popups; these windows are always on top of 'Normal' windows.
/// The base class <see cref="Popup"/> was not designed to behave this way.
/// In the base class, when the popup is opened, a call to set the window's [z]position (<see cref="NativeMethods.SetWindowPos(IntPtr, IntPtr, int, int, int, int, SWP)"/>)
/// is made with <see cref="NativeMethods.HWND_TOPMOST"/> as the 'insertAfter' param (just before this method is called).
/// Positioning the popup window just above the main window (wrt z order) requires 2 calls:
/// 1) a call to remove it from the 'TopMost' group (this call is idempotent and safe to make every time the popup is displayed),
/// 2) a call to set it on top of the 'Normal' windows.
_set_top_most(NativeMethods.HWND_NOTOPMOST, "intializing z position on opened (1/2)");
}
static string _win_handle_name(IntPtr? handle) {
if (handle.HasValue) {
if (handle.Value == NativeMethods.HWND_BOTTOM)
return "Bottom";
if (handle.Value == NativeMethods.HWND_TOP)
return "Top";
if (handle.Value == NativeMethods.HWND_TOPMOST)
return "TopMost";
if (handle.Value == NativeMethods.HWND_NOTOPMOST)
return "NoTopMost";
return "Custom";
}
return "Null";
}
void _on_unsafe_window_changed(object sender, RoutedPropertyChangedEventArgs<Window> e) =>
_on_window(e.NewValue);
async void _on_window(Window win, bool reopen = true) {
Disposable.dispose(ref _window_sub);
var old_win = _window;
_window = win;
if (win == null)
return;
/// the lock object can be local to this method,
/// bc <see cref="_window_sub"/> will [always]be disposed on the same thread (this instance's dispatcher).
object locker = new object();
bool cancel = false;
Action unhook = null;
if (reopen && IsOpen && old_win != null) {
// close then reopen to force the base class to detach from the old presentation source
// then reattach to the new one
_log.info("Parent window changed - closing then reopneing popup to detach from previous parent's presentation source.");
_is_parent_changing = true;
SetCurrentValue(IsOpenProperty, false);
/// Use <see cref="DispatcherPriority.ApplicationIdle"/> priority to ensure that the
/// base class's calls to detach the popup from the old presentation source are executed before the popup is reopened.
/// This is not a time sensitive op, so ApplicationIdle might be the most apprioriate priority regardless.
await Dispatcher.InvokeAsync(() => {
SetCurrentValue(IsOpenProperty, true);
_is_parent_changing = false;
}, DispatcherPriority.ApplicationIdle);
}
_window_sub = Disposable.Create(() => {
lock (locker) {
if (unhook != null) {
unhook();
unhook = null;
} else {
cancel = true;
}
}
});
await win.Dispatcher.InvokeAsync(() => {
lock (locker) {
if (!cancel) {
win.Activated += on_activated;
win.Deactivated += on_deactivated;
win.StateChanged += on_state_changed;
if (win.IsActive) {
_set_top_most(NativeMethods.HWND_TOPMOST, "new parent window is [initially] active");
}
unhook = () => {
win.Dispatcher.InvokeAsync(() => {
win.Activated -= on_activated;
win.Deactivated -= on_deactivated;
win.StateChanged -= on_state_changed;
});
};
}
void on_activated(object sender, EventArgs e) =>
_set_top_most(NativeMethods.HWND_TOPMOST, "parent window activated");
void on_deactivated(object sender, EventArgs e) {
_set_top_most(NativeMethods.HWND_NOTOPMOST, "parent window deactivated 1/2");
_set_top_most(NativeMethods.HWND_TOP, "parent window deactivated 2/2");
}
void on_state_changed(object sender, EventArgs e) {
switch (win.WindowState) {
case WindowState.Minimized: {
if (_try_get_handle(out var handle))
NativeMethods.ShowWindow(new HandleRef(null, handle), (int)SW.SW_HIDE);
}
break;
case WindowState.Maximized:
case WindowState.Normal: {
if (_try_get_handle(out var handle))
NativeMethods.ShowWindow(new HandleRef(null, handle), (int)SW.SW_SHOW);
}
break;
}
}
}
});
}
void _set_top_most(IntPtr? insert_after = null, string reason = "n/a") {
var flags = SWP.TOPMOST_FLAGS;
if (!Dispatcher.CheckAccess()) {
flags |= SWP.SWP_ASYNCWINDOWPOS;
}
if (!_try_get_insert_after(insert_after, out var ia_handle)) {
_log.info($"Ignored setting top most because an explicit 'insert after' handle was not specified, and the parent window's handle was not found - reason (for attempt): {reason}.");
} else if (_try_get_handle(out var handle) && NativeMethods.GetWindowRect(handle, out var rect)) {
_log.info($"setting top most - reason: {reason}; insert after handle: {_win_handle_name(insert_after)}.");
NativeMethods.SetWindowPos(handle, ia_handle, rect.Left, rect.Top, (int)Width, (int)Height, flags);
} else {
_log.info($"Ignored setting top most because the child window's handle was not found - reason (for attempt): {reason}; insert after handle: {_win_handle_name(insert_after)}.");
}
}
bool _try_get_handle(out IntPtr handle) {
if (Child != null && PresentationSource.FromVisual(Child) is HwndSource hwnd) {
handle = hwnd.Handle;
return true;
}
handle = default;
return false;
}
bool _try_get_insert_after(IntPtr? curr, out IntPtr result) {
if (curr.HasValue) {
result = curr.Value;
} else if (_window != null && PresentationSource.FromVisual(_window) is HwndSource hwnd) {
result = hwnd.Handle;
} else {
result = default;
return false;
}
return true;
}
}
}
@@ -55,6 +55,7 @@
<SolidColorBrush Color="{StaticResource MouseOverBorderLightColor}"/> <SolidColorBrush Color="{StaticResource MouseOverBorderLightColor}"/>
</Setter.Value> </Setter.Value>
</Setter> </Setter>
<Setter Property="Background" Value="{u:BTSColor UI.Button.mouseover_background}"/>
</Trigger> </Trigger>
<Trigger Property="IsEnabled" Value="False"> <Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.5"/> <Setter Property="Opacity" Value="0.5"/>
@@ -62,6 +63,67 @@
</Style.Triggers> </Style.Triggers>
</Style> </Style>
<Style x:Key="SparkToolBarButton" TargetType="Button">
<Setter Property="ToolTipService.ShowOnDisabled" Value="True"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Height" Value="22"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Padding" Value="2"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Width" Value="22"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
x:Name="Border"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Opacity="1"
>
<Border.BorderBrush>
<SolidColorBrush/>
</Border.BorderBrush>
<Border.Background>
<SolidColorBrush/>
</Border.Background>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal"/>
<VisualState Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{DynamicResource Control.AlphaLightMediumGrayColor}"/>
<ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" BeginTime="0" Duration="0" To="{DynamicResource Control.DarkGrayColor}"/>
</Storyboard>
</VisualState>
<VisualState Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color" BeginTime="0" Duration="0" To="{DynamicResource Control.AlphaMediumGrayColor}"/>
<ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" BeginTime="0" Duration="0" To="{DynamicResource Control.DarkGrayColor}"/>
</Storyboard>
</VisualState>
<VisualState Name="Disabled">
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="0.52"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentPresenter
Name="presenter"
Grid.Column="1"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True"
/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ToolBarThumbStyle" TargetType="{x:Type Thumb}"> <Style x:Key="ToolBarThumbStyle" TargetType="{x:Type Thumb}">
<Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Cursor" Value="SizeAll"/> <Setter Property="Cursor" Value="SizeAll"/>
@@ -222,4 +284,4 @@
</Setter.Value> </Setter.Value>
</Setter> </Setter>
</Style> </Style>
</ResourceDictionary> </ResourceDictionary>
@@ -0,0 +1,37 @@
using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using System.Windows.Media;
namespace mbts.ui.converters {
class ColorBlendConverter : IValueConverter {
public Color Overlay { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is Color color ? color.blend(Overlay) : Overlay;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
class ColorWithConverter : IValueConverter {
public byte? A { get; set; }
public byte? R { get; set; }
public byte? G { get; set; }
public byte? B { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is Color c ? c.with(A, R, G, B) : value;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
class ColorBlendMultiConverter : IMultiValueConverter {
public static ColorBlendMultiConverter Instance => new ColorBlendMultiConverter();
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) =>
values.OfType<Color>().Aggregate(Colors.Transparent, WPFExtensions.blend);
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
}
@@ -5,11 +5,11 @@ using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Media; using System.Windows.Media;
namespace mbts.ui.converters namespace mbts.ui.converters {
{
[ValueConversion(typeof(ImageSource), typeof(Image))] [ValueConversion(typeof(ImageSource), typeof(Image))]
internal class ImageSourceIconConverter : IValueConverter class ImageSourceIconConverter : IValueConverter {
{ public static ImageSourceIconConverter Instance => new ImageSourceIconConverter();
public Thickness Margin { get; set; } = new Thickness(0); public Thickness Margin { get; set; } = new Thickness(0);
public double Width { get; set; } = double.NaN; public double Width { get; set; } = double.NaN;
public double Height { get; set; } = double.NaN; public double Height { get; set; } = double.NaN;
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace mbts.ui.converters {
[ValueConversion(typeof(double), typeof(double))]
class MaximumConverter : IMultiValueConverter {
public static MaximumConverter Instance =>
new MaximumConverter();
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) =>
values.OfTypeSafe<IComparable>().Max();
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
}
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace mbts.ui.converters {
[ValueConversion(typeof(double), typeof(double))]
class MinimumConverter : IMultiValueConverter {
public static MinimumConverter Instance =>
new MinimumConverter();
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) =>
values.OfTypeSafe<IComparable>().Min();
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
}
@@ -14,7 +14,6 @@ namespace mbts.ui.converters {
return new ValidationResult(false, "Not a double."); return new ValidationResult(false, "Not a double.");
} }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is double d) if (value is double d)
return d + Value; return d + Value;
@@ -24,12 +23,22 @@ namespace mbts.ui.converters {
[ValueConversion(typeof(double[]), typeof(double))] [ValueConversion(typeof(double[]), typeof(double))]
class DoubleDynamicSubtractionConverter : IMultiValueConverter { class DoubleDynamicSubtractionConverter : IMultiValueConverter {
public static DoubleDynamicSubtractionConverter Instance => new DoubleDynamicSubtractionConverter();
public double Minimum { get; set; } = double.NaN;
public double Maximum { get; set; } = double.NaN;
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
if (values.Length > 0 && values[0] is double difference) { if (values.Length > 0 && values[0] is double difference) {
for (int i = 1; i < values.Length; i++) { for (int i = 1; i < values.Length; i++) {
if (values[i] is double v) if (values[i] is double v)
difference -= v; difference -= v;
} }
if (Minimum.IsReal() && difference < Minimum) {
return Minimum;
} else if (Maximum.IsReal() && difference > Maximum) {
return Maximum;
}
return difference; return difference;
} }
return new ValidationResult(false, "No doubles."); return new ValidationResult(false, "No doubles.");
@@ -38,4 +47,4 @@ namespace mbts.ui.converters {
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
@@ -0,0 +1,46 @@
using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
namespace mbts.ui.converters {
class RangeBlockConverter : IValueConverter {
public IComparable Minimum { get; set; }
public IComparable Maximum { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is IComparable comp) {
if (Minimum != null && comp.CompareTo(Minimum) < 0)
return Minimum;
if (Maximum != null && comp.CompareTo(Maximum) > 0)
return Maximum;
} else {
return new ValidationResult(false, $"Value does not implement {typeof(IComparable)}.");
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotImplementedException();
}
class RangeBlockConverter<T> : IValueConverter where T : struct, IComparable<T> {
public T? Maximum { get; set; }
public T? Minimum { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is T v) {
if (Minimum.HasValue && v.CompareTo(Minimum.Value) < 0)
return Minimum.Value;
if (Maximum.HasValue && v.CompareTo(Maximum.Value) > 0)
return Maximum.Value;
} else {
return new ValidationResult(false, $"Value is not of type {typeof(T)}.");
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotImplementedException();
}
}
@@ -2,6 +2,7 @@
using bts.utils; using bts.utils;
using mbts.ui.extensions; using mbts.ui.extensions;
using mbts.ui.shell; using mbts.ui.shell;
using mbts.ui.utilities;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Reactive.Linq; using System.Reactive.Linq;
@@ -68,16 +69,37 @@ namespace mbts.ui {
} }
}); });
public static IObservable<Point?> subscribe_drag_coordinates(FrameworkElement element) => public static IObservable<Point?> subscribe_drag_coordinates(
Observable.Create<Point?>(o => { FrameworkElement element,
FrameworkElement init_element = null,
Rect? drag_start_bounds = null,
bool use_preview_events = false,
MouseButton mouse_button = MouseButton.Left) {
if (element == null)
throw new ArgumentNullException(nameof(element));
if (init_element == null)
init_element = element;
return Observable.Create<Point?>(o => {
Point? mouse_down = null, drag_start = null; Point? mouse_down = null, drag_start = null;
element.MouseDown += on_mouse_down; if (use_preview_events) {
element.MouseMove += on_mouse_move; init_element.PreviewMouseDown += on_mouse_down;
element.MouseUp += on_mouse_up; element.PreviewMouseMove += on_mouse_move;
element.PreviewMouseUp += on_mouse_up;
} else {
init_element.MouseDown += on_mouse_down;
element.MouseMove += on_mouse_move;
element.MouseUp += on_mouse_up;
}
return Disposable.Create(() => { return Disposable.Create(() => {
element.MouseDown -= on_mouse_down; if (use_preview_events) {
element.MouseMove -= on_mouse_move; init_element.PreviewMouseDown -= on_mouse_down;
element.MouseUp -= on_mouse_up; element.PreviewMouseMove -= on_mouse_move;
element.PreviewMouseUp -= on_mouse_up;
} else {
init_element.MouseDown -= on_mouse_down;
element.MouseMove -= on_mouse_move;
element.MouseUp -= on_mouse_up;
}
}); });
// callbacks // callbacks
void on_mouse_up(object sender, MouseButtonEventArgs e) { void on_mouse_up(object sender, MouseButtonEventArgs e) {
@@ -87,7 +109,7 @@ namespace mbts.ui {
} }
void on_mouse_move(object sender, MouseEventArgs e) { void on_mouse_move(object sender, MouseEventArgs e) {
if (drag_start.HasValue) { if (drag_start.HasValue) {
o.OnNext(Mouse.LeftButton == MouseButtonState.Pressed ? e.GetPosition(element) : (drag_start = null)); o.OnNext(MouseHelper.button_state(mouse_button) == MouseButtonState.Pressed ? e.GetPosition(element) : (drag_start = null));
e.Handled = true; e.Handled = true;
} else if (mouse_down.HasValue) { } else if (mouse_down.HasValue) {
var curr_pt = e.GetPosition(element); var curr_pt = e.GetPosition(element);
@@ -100,10 +122,14 @@ namespace mbts.ui {
} }
} }
void on_mouse_down(object sender, MouseButtonEventArgs e) { void on_mouse_down(object sender, MouseButtonEventArgs e) {
drag_start = null; var pt = e.GetPosition(init_element);
mouse_down = e.GetPosition(element); if (!drag_start_bounds.HasValue || drag_start_bounds.Value.Contains(pt)) {
drag_start = null;
mouse_down = pt;
}
} }
}); });
}
public static IDisposable connect_horizontal_insertion_adorner(ItemsControl container, FrameworkElement root = null) { public static IDisposable connect_horizontal_insertion_adorner(ItemsControl container, FrameworkElement root = null) {
HorizontalInsertionAdorner insertion_adorner = null; HorizontalInsertionAdorner insertion_adorner = null;
@@ -339,6 +365,7 @@ namespace mbts.ui {
} }
new_window.move_to_mouse(); new_window.move_to_mouse();
new_window.Visibility = Visibility.Visible; new_window.Visibility = Visibility.Visible;
new_window.Activate();
} }
} }
} }
@@ -9,6 +9,20 @@ using CompositeDisposable = System.Reactive.Disposables.CompositeDisposable;
namespace mbts.ui.extensions { namespace mbts.ui.extensions {
static class FrameworkElementHelper { static class FrameworkElementHelper {
public static Point GetCenter(this FrameworkElement element) =>
new Point(element.ActualWidth * 0.5, element.ActualHeight * 0.5);
public static Point GetChildCenter(this UIElement parent, FrameworkElement child) =>
child.TranslatePoint(GetCenter(child), parent);
public static Point GetChildTopLeft(this UIElement parent, FrameworkElement child) =>
child.TranslatePoint(new Point(0, 0), parent);
public static Rect GetChildBounds(this UIElement target, FrameworkElement child) {
var child_tl = target.GetChildTopLeft(child);
return new Rect(child_tl.X, child_tl.Y, child.ActualWidth, child.ActualHeight);
}
/// <summary> /// <summary>
/// Invokes the specified action immediately if the element is already loaded, otherwise hooks up to the <see cref="FrameworkElement.Loaded"/> event, /// Invokes the specified action immediately if the element is already loaded, otherwise hooks up to the <see cref="FrameworkElement.Loaded"/> event,
/// and [conditionally]invokes the specified action if <paramref name="should_still_execute"/> returns true. /// and [conditionally]invokes the specified action if <paramref name="should_still_execute"/> returns true.
@@ -32,20 +46,6 @@ namespace mbts.ui.extensions {
} }
} }
public static Point GetCenter(this FrameworkElement element) =>
new Point(element.ActualWidth * 0.5, element.ActualHeight * 0.5);
public static Point GetChildCenter(this UIElement parent, FrameworkElement child) =>
child.TranslatePoint(GetCenter(child), parent);
public static Point GetChildTopLeft(this UIElement parent, FrameworkElement child) =>
child.TranslatePoint(new Point(0, 0), parent);
public static Rect GetChildBounds(this UIElement target, FrameworkElement child) {
var child_tl = target.GetChildTopLeft(child);
return new Rect(child_tl.X, child_tl.Y, child.ActualWidth, child.ActualHeight);
}
public static IDisposable SubscribeLoaded(this FrameworkElement element, RoutedEventHandler callback) { public static IDisposable SubscribeLoaded(this FrameworkElement element, RoutedEventHandler callback) {
element.Loaded += callback; element.Loaded += callback;
return Disposable.Create(() => element.Loaded -= callback); return Disposable.Create(() => element.Loaded -= callback);
@@ -146,10 +146,14 @@ namespace mbts.ui.extensions {
element.Loaded += on_loaded; element.Loaded += on_loaded;
if (disconnect_on_unloaded) if (disconnect_on_unloaded)
element.Unloaded += on_unloaded; element.Unloaded += on_unloaded;
if (element.IsLoaded)
connection = connect();
return Disposable.Create(dispose); return Disposable.Create(dispose);
void on_loaded(object sender, RoutedEventArgs e) => void on_loaded(object sender, RoutedEventArgs e) {
Disposable.replace(ref connection, connect()); connection?.Dispose();
connection = connect();
}
void on_unloaded(object sender, RoutedEventArgs e) => void on_unloaded(object sender, RoutedEventArgs e) =>
Disposable.dispose(ref connection); Disposable.dispose(ref connection);
@@ -1,18 +1,26 @@
using mbts.config; using bts.utils;
using mbts.config;
using mbts.ui.controls;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Windows;
using System.Windows.Forms; using System.Windows.Forms;
using System.Windows.Media;
using Point = System.Windows.Point;
namespace mbts.ui.dpi { namespace mbts.ui.dpi {
public static class HighDpiExtensions { public static class HighDpiExtensions {
public static readonly double dpi_ratio; public static readonly double
dpi_ratio,
pixel_unit;
public static readonly float fdpi_ratio; public static readonly float fdpi_ratio;
static HighDpiExtensions() { static HighDpiExtensions() {
dpi_ratio = Configuration.get<bts.config.System>().dpi_ratio; dpi_ratio = Configuration.get<bts.config.System>().dpi_ratio;
pixel_unit = 1 / dpi_ratio;
fdpi_ratio = (float)dpi_ratio; fdpi_ratio = (float)dpi_ratio;
} }
@@ -119,5 +127,126 @@ namespace mbts.ui.dpi {
} }
} }
#endregion #endregion
public static Point PointToScreenPixels(this Visual visual, double x, double y) =>
PointToScreenPixels(visual, new Point(x, y));
public static Point PointToScreenPixels(this Visual visual, Point point) {
var pt = visual.PointToScreen(point);
return new Point(pt.X * pixel_unit, pt.Y * pixel_unit);
}
/// <summary>
/// Calculates the value to be used for layout rounding at high DPI.
/// </summary>
/// <param name="value">Input value to be rounded.</param>
/// <param name="dpiScale">Ratio of screen's DPI to layout DPI</param>
/// <returns>Adjusted value that will produce layout rounding on screen at high dpi.</returns>
/// <remarks>This is a layout helper method. It takes DPI into account and also does not return
/// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper associated with
/// UseLayoutRounding property and should not be used as a general rounding utility.</remarks>
public static double RoundLayoutValue(this double value) =>
RoundLayoutValue(value, dpi_ratio);
public static double RoundLayoutValue(double value, double dpiScale) {
if (DoubleUtil.AreClose(dpiScale, 1.0))
return Math.Round(value);
double result = Math.Round(value * dpiScale) / dpiScale;
return DoubleHelper.IsNaNOrInfinity(result) || DoubleUtil.AreClose(result, double.MaxValue) ? value : result;
}
public static Point RoundToLayout(this Point point) =>
new Point(RoundLayoutValue(point.X), RoundLayoutValue(point.Y));
public static Rect RoundToLayout(this Rect rect) =>
new Rect(rect.TopLeft.RoundToLayout(), rect.Size.RoundToLayout());
public static System.Windows.Size RoundToLayout(this System.Windows.Size size) =>
new System.Windows.Size(size.Width.RoundLayoutValue(), size.Height.RoundLayoutValue());
public static Thickness RoundToLayout(this Thickness thickness) =>
new Thickness(
thickness.Left.RoundLayoutValue(),
thickness.Top.RoundLayoutValue(),
thickness.Right.RoundLayoutValue(),
thickness.Bottom.RoundLayoutValue());
public static GuidelineSet AntiAliasGuidelines(this Rect rect) =>
rect.AntiAliasGuidelines(dpi_ratio);
public static GuidelineSet AntiAliasGuidelines(this Rect rect, double pen_thickness) {
var half_pen_thickness = pen_thickness / 2;
//half_pen_thickness = 0;
var guidelines = new GuidelineSet(
new[] { rect.Left.RoundLayoutValue() - half_pen_thickness, rect.Right.RoundLayoutValue() + half_pen_thickness },
new[] { rect.Top.RoundLayoutValue() - half_pen_thickness, rect.Bottom.RoundLayoutValue() + half_pen_thickness });
return guidelines;
}
public static void DrawHorizontalLine(this DrawingContext drawing_context, System.Windows.Media.Pen pen, Point start, double length, bool snap_to_device_pixels) {
if (pen == null || !length.IsRealNonZero()) {
// no need to flip out and throw an exception
return;
}
if (snap_to_device_pixels) {
start = start.RoundToLayout();
var half_pen = pen.Thickness / 2;
var stop = new Point((start.X + length).RoundLayoutValue(), start.Y);
var (left_edge, right_edge) = MathUtils.get_outliers(start.X, stop.X);
var guidelines = new GuidelineSet(
new[] { left_edge + half_pen, right_edge - half_pen },
new[] { start.Y - half_pen });
drawing_context.PushGuidelineSet(guidelines);
drawing_context.DrawLine(pen, start, stop);
drawing_context.Pop();
} else {
drawing_context.DrawLine(pen, start, new Point(start.X + length, start.Y));
}
}
public static void DrawLine(this DrawingContext drawing_context, System.Windows.Media.Pen pen, Point point0, Point point1, bool snap_to_device_pixels) {
if (pen == null) {
// no need to flip out and throw an exception
return;
}
if (snap_to_device_pixels) {
point0 = point0.RoundToLayout();
point1 = point1.RoundToLayout();
var (left_edge, right_edge) = MathUtils.get_outliers(point0.X, point1.X);
var (top_edge, bottom_edge) = MathUtils.get_outliers(point0.Y, point1.Y);
var x = point0.X;
var y = point0.Y;
var half_pen = pen.Thickness / 2;
drawing_context.PushGuidelineSet(new GuidelineSet(
new[] { left_edge + half_pen, right_edge - half_pen },
new[] { top_edge + half_pen, bottom_edge - half_pen }));
drawing_context.DrawLine(pen, point0, point1);
drawing_context.Pop();
} else {
drawing_context.DrawLine(pen, point0, point1);
}
}
public static void DrawRectangle(this DrawingContext drawing_context, System.Windows.Media.Brush brush, System.Windows.Media.Pen pen, Rect rectangle, bool snap_to_device_pixels) {
if ((brush == null && pen == null) || rectangle.IsEmpty) {
// no need to flip out and throw an exception
return;
}
if (snap_to_device_pixels) {
if (pen != null) {
if (rectangle.Width > pen.Thickness && rectangle.Height > pen.Thickness) {
var half_pen = pen.Thickness / 2;
rectangle = rectangle.RoundToLayout();
rectangle = new Rect(rectangle.Left + half_pen, rectangle.Top + half_pen, rectangle.Width - pen.Thickness, rectangle.Height - pen.Thickness);
drawing_context.DrawRectangle(brush, pen, rectangle);
}
} else {
drawing_context.PushGuidelineSet(rectangle.AntiAliasGuidelines(0));
drawing_context.DrawRectangle(brush, pen, rectangle);
drawing_context.Pop();
}
} else {
drawing_context.DrawRectangle(brush, pen, rectangle);
}
}
} }
} }
@@ -2,17 +2,12 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup; using System.Windows.Markup;
using System.Windows.Media; using System.Windows.Media;
namespace mbts.ui namespace mbts.ui {
{
[MarkupExtensionReturnType(typeof(Brush))] [MarkupExtensionReturnType(typeof(Brush))]
public class BrushExtension : MarkupExtension class BrushExtension : MarkupExtension {
{
public BrushExtension() : this(Colors.Black) { } public BrushExtension() : this(Colors.Black) { }
public BrushExtension(Color Color) : this(Color, 1.0) { } public BrushExtension(Color Color) : this(Color, 1.0) { }
public BrushExtension(Color Color, double Opacity) { this.Color = Color; this.Opacity = Opacity; } public BrushExtension(Color Color, double Opacity) { this.Color = Color; this.Opacity = Opacity; }
@@ -20,11 +15,14 @@ namespace mbts.ui
[TypeConverter(typeof(ColorTypeConverter))] [TypeConverter(typeof(ColorTypeConverter))]
[ConstructorArgument("Color")] [ConstructorArgument("Color")]
public Color Color { get; set; } public Color Color { get; set; }
[ConstructorArgument("Opacity")] [ConstructorArgument("Opacity")]
public double Opacity { get; set; } public double Opacity { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider) {
return new SolidColorBrush(Color) { Opacity = Opacity }; public bool Freeze { get; set; }
}
public override object ProvideValue(IServiceProvider serviceProvider) =>
Freeze ? FrozenBrushCache.get_brush(Color, Opacity) : new SolidColorBrush(Color) { Opacity = Opacity };
} }
public class ColorTypeConverter : TypeConverter public class ColorTypeConverter : TypeConverter
@@ -1,4 +1,5 @@
using mbts.ui.utility.text; using bts.utils;
using mbts.ui.utility.text;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -11,26 +12,35 @@ using System.Windows.Media;
namespace mbts.ui.extensions { namespace mbts.ui.extensions {
public static class UIElementExtensions { public static class UIElementExtensions {
public static bool ChildAtPoint<T>(this UIElement target, Point pt, out T result) where T : DependencyObject { public static bool ChildAtPoint<T>(this UIElement target, Point pt, out T result) where T : DependencyObject {
if (target.InputHitTest(pt) is UIElement source) { result = target.ChildAtPoint<T>(pt);
result = source as T ?? FindAncestor<T>(source); return result != null;
return result != null;
}
result = default;
return false;
} }
public static T ChildAtPoint<T>(this UIElement target, Point pt) where T : DependencyObject { public static T ChildAtPoint<T>(this UIElement element, Point pt) where T : DependencyObject =>
var source = target.InputHitTest(pt) as UIElement; element.IsWithinBounds(pt) && element.InputHitTest(pt) is UIElement hit ?
if (source == null) return null; (hit == element ? null : hit as T ?? FindAncestor<T>(hit)) :
if (source is T) return source as T; null;
return FindAncestor<T>(source);
public static T FindAncestor<T>(this DependencyObject dependency_object) where T : DependencyObject =>
dependency_object == null ? null :
dependency_object as T ?? FindAncestor<T>(VisualTreeHelper.GetParent(dependency_object));
public static Point GetCenter(this UIElement element) =>
new Point(element.RenderSize.Width * 0.5, element.RenderSize.Height * 0.5);
public static Point GetChildCenter(this UIElement parent, UIElement child) =>
child.TranslatePoint(GetCenter(child), parent);
public static Point GetChildTopLeft(this UIElement parent, UIElement child) =>
child.TranslatePoint(new Point(0, 0), parent);
public static Rect GetChildBounds(this UIElement target, UIElement child) {
var child_tl = target.GetChildTopLeft(child);
return new Rect(child_tl.X, child_tl.Y, child.RenderSize.Width, child.RenderSize.Height);
} }
public static T FindAncestor<T>(this DependencyObject target) where T : DependencyObject { public static bool IsWithinBounds(this UIElement target, Point pt) =>
if (target == null) return null; pt.X >= 0 && pt.X < target.RenderSize.Width && pt.Y >= 0 && pt.Y < target.RenderSize.Height;
if (target is T) return (T)target;
return FindAncestor<T>(VisualTreeHelper.GetParent(target)) ?? FindAncestor<T>(LogicalTreeHelper.GetParent(target));
}
public static IEnumerable<DependencyObject> VisualAncestors(this DependencyObject dependency_object) { public static IEnumerable<DependencyObject> VisualAncestors(this DependencyObject dependency_object) {
var parent = VisualTreeHelper.GetParent(dependency_object); var parent = VisualTreeHelper.GetParent(dependency_object);
@@ -47,6 +57,22 @@ namespace mbts.ui.extensions {
public static IDisposable DeferInvalidateVisual(this UIElement target) => public static IDisposable DeferInvalidateVisual(this UIElement target) =>
Disposable.Create(target.InvalidateVisual); Disposable.Create(target.InvalidateVisual);
public static IObservable<Point> ObserveTopLeft(this Window win) =>
Observable.Create<Point>(o => {
var last_pt = new Point(win.Left, win.Top);
o.OnNext(last_pt);
win.LocationChanged += on_location_changed;
return Disposable.Create(() => win.LocationChanged -= on_location_changed);
void on_location_changed(object sender, EventArgs e) =>
notify();
void notify() {
if (Swap.compare_exchange(ref last_pt, new Point(win.Left, win.Top)))
o.OnNext(last_pt);
}
});
public static IDisposable SubscribeGotFocus(this UIElement target, RoutedEventHandler callback) { public static IDisposable SubscribeGotFocus(this UIElement target, RoutedEventHandler callback) {
target.GotFocus += callback; target.GotFocus += callback;
return Disposable.Create(() => target.GotFocus -= callback); return Disposable.Create(() => target.GotFocus -= callback);
@@ -77,6 +103,11 @@ namespace mbts.ui.extensions {
return Disposable.Create(() => target.MouseUp -= callback); return Disposable.Create(() => target.MouseUp -= callback);
} }
public static IDisposable SubscribeMouseLeftButtonDown(this UIElement target, MouseButtonEventHandler callback) {
target.MouseLeftButtonDown += callback;
return Disposable.Create(() => target.MouseLeftButtonDown -= callback);
}
public static IDisposable SubscribeMouseLeftButtonUp(this UIElement target, MouseButtonEventHandler callback) { public static IDisposable SubscribeMouseLeftButtonUp(this UIElement target, MouseButtonEventHandler callback) {
target.MouseLeftButtonUp += callback; target.MouseLeftButtonUp += callback;
return Disposable.Create(() => target.MouseLeftButtonUp -= callback); return Disposable.Create(() => target.MouseLeftButtonUp -= callback);
@@ -1,7 +1,6 @@
using bts; using bts;
using bts.collections; using bts.collections;
using bts.utils; using bts.utils;
using mbts.ui.utility;
using mbts.utils; using mbts.utils;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -19,6 +18,29 @@ using System.Windows.Media;
namespace mbts.ui { namespace mbts.ui {
static class WPFExtensions { static class WPFExtensions {
public static void bind(this DependencyObject target, DependencyProperty property, IValueConverter converter = null, object source = null, string path = null, params object[] path_parameters) {
var pp = new PropertyPath(path ?? string.Join(".", Array.ConvertAll(path_parameters, i => $"({i})")));
for (int i = 0; i < path_parameters.Length; i++)
pp.PathParameters.Add(path_parameters[i]);
bind(target, property, pp, converter: converter, source: source);
}
public static void bind(this DependencyObject target, DependencyProperty property, PropertyPath path, IValueConverter converter = null, object source = null) =>
BindingOperations.SetBinding(target, property, new Binding {
Path = path,
Source = source,
Converter = converter
});
public static (double x, double y) deconstruct(this Point point) =>
(point.X, point.Y);
public static Point minus(this Point point, Point other) =>
new Point(point.X - other.X, point.Y - other.Y);
public static Point plus(this Point point, Point other) =>
new Point(point.X + other.X, point.Y + other.Y);
public static object get_template_child(this Control control, string name) { public static object get_template_child(this Control control, string name) {
if (control == null) throw new ArgumentNullException(nameof(control)); if (control == null) throw new ArgumentNullException(nameof(control));
return control?.Template?.FindName(name, control); return control?.Template?.FindName(name, control);
@@ -110,8 +132,23 @@ namespace mbts.ui {
return brush; return brush;
} }
public static Color with(this Color color, byte alpha) => public static Color blend(this Color color, Color other) {
Color.FromArgb(alpha, color.R, color.G, color.B); // it doesn't make sense to avg the Alpha value (layering transparent over an opaque color should yield the opaque color).
// just apply the max Alpha to the resultant color
if (color.A == 0)
return other;
if (other.A == 0)
return color;
var color_opac = color.A / 255.0;
var other_opac = other.A / 255.0;
var avg_red = (byte)new[] { (color.R, color.A), (other.R, other.A) }.weighted_average(tup => tup.R, tup => tup.A);
var avg_green = (byte)new[] { (color.G, color.A), (other.G, other.A) }.weighted_average(tup => tup.G, tup => tup.A);
var avg_blue = (byte)new[] { (color.B, color.A), (other.B, other.A) }.weighted_average(tup => tup.B, tup => tup.A);
return Color.FromArgb(Math.Max(color.A, other.A), avg_red, avg_green, avg_blue);
}
public static Color with(this Color color, byte? alpha = null, byte? red = null, byte? green = null, byte? blue = null) =>
Color.FromArgb(alpha ?? color.A, red ?? color.R, green ?? color.G, blue ?? color.B);
public static SolidColorBrush with(this SolidColorBrush brush, double opacity) { public static SolidColorBrush with(this SolidColorBrush brush, double opacity) {
brush.Opacity = opacity; brush.Opacity = opacity;
@@ -595,6 +595,54 @@
</Style.Triggers> </Style.Triggers>
</Style> </Style>
<ControlTemplate x:Key="BuyButtonTemplate" TargetType="Button">
<Border
x:Name="Border"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="True"
>
<ContentPresenter
Name="button_content"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True"
/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="Background" Value="#99167ed3"/>
<Setter TargetName="Border" Property="BorderBrush" Value="{mbts:BTSColor UI.Button.mouseover_border}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<ControlTemplate x:Key="SellButtonTemplate" TargetType="Button">
<Border
x:Name="Border"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="True"
>
<ContentPresenter
Name="button_content"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True"
/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="Background" Value="#99c00000" />
<Setter TargetName="Border" Property="BorderBrush" Value="{mbts:BTSColor UI.Button.mouseover_border}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<Style x:Key="CommonButton" BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type Button}"> <Style x:Key="CommonButton" BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type Button}">
<Setter Property="MinWidth" Value="60" /> <Setter Property="MinWidth" Value="60" />
<Setter Property="Margin" Value="4" /> <Setter Property="Margin" Value="4" />
@@ -17,6 +17,30 @@ namespace mbts.ui {
MinimizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = WindowState.Minimized), MinimizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = WindowState.Minimized),
MaximizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = w.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized); MaximizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = w.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized);
#region UnsafeWindow
// UnsafeWindow is described as 'Unsafe' because the window may be on a different dispatcher than the DependencyObject target.
public static readonly DependencyProperty UnsafeWindowProperty =
DependencyProperty.RegisterAttached("UnsafeWindow", typeof(Window), typeof(WindowStyle), new PropertyMetadata(OnUnsafeWindowChanged));
static void OnUnsafeWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (d is UIElement el)
el.RaiseEvent(new RoutedPropertyChangedEventArgs<Window>(e.OldValue as Window, e.NewValue as Window, UnsafeWindowChangedEvent));
}
public static Window GetUnsafeWindow(DependencyObject d) => d.GetValue(UnsafeWindowProperty) as Window;
public static void SetUnsafeWindow(DependencyObject d, Window value) => d.SetValue(UnsafeWindowProperty, value);
#endregion
#region UnsafeWindowChanged (Event)
internal static readonly RoutedEvent UnsafeWindowChangedEvent = EventManager.RegisterRoutedEvent("UnsafeWindowChanged", RoutingStrategy.Direct, typeof(RoutedPropertyChangedEventHandler<Window>), typeof(WindowStyle));
internal static void AddUnsafeWindowChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<Window> handler) =>
el.AddHandler(UnsafeWindowChangedEvent, handler);
internal static void RemoveUnsafeWindowChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<Window> handler) =>
el.RemoveHandler(UnsafeWindowChangedEvent, handler);
#endregion
static class WindowCallbackHelper { static class WindowCallbackHelper {
public static ExecutedRoutedEventHandler safe_command_executed_handler(Action<Window> action, string action_name) => public static ExecutedRoutedEventHandler safe_command_executed_handler(Action<Window> action, string action_name) =>
(s, e) => _safe_execute_on_window(s, action, action_name); (s, e) => _safe_execute_on_window(s, action, action_name);
@@ -109,6 +109,7 @@ namespace mbts.ui.shell
this.Items.Remove(document); this.Items.Remove(document);
document.ViewModel.Closing -= TabClosing; document.ViewModel.Closing -= TabClosing;
document.ViewModel.host_id = string.Empty; document.ViewModel.host_id = string.Empty;
document.ViewModel.owner = null;
if (IsEmpty && !IsClosed) { if (IsEmpty && !IsClosed) {
this.Close(); this.Close();
} }
@@ -117,6 +118,7 @@ namespace mbts.ui.shell
// if is_loaded is true, will NOT set width/height // if is_loaded is true, will NOT set width/height
public async Task add_document(TabDocument document, int index, bool is_loaded=false) { public async Task add_document(TabDocument document, int index, bool is_loaded=false) {
Log.assert(document.Parent == null); Log.assert(document.Parent == null);
document.ViewModel.owner = this;
// Manually copy over the initial size if this is a new Window // Manually copy over the initial size if this is a new Window
if (_tabs.Items.Count == 0 && !is_loaded) if (_tabs.Items.Count == 0 && !is_loaded)
await _size_to_content(document); await _size_to_content(document);
@@ -361,7 +361,6 @@
<scm:SortDescription PropertyName="id"/> <scm:SortDescription PropertyName="id"/>
</CollectionViewSource.SortDescriptions> </CollectionViewSource.SortDescriptions>
</CollectionViewSource> </CollectionViewSource>
<SolidColorBrush x:Key="SeparatorFill" Color="Black"/>
</Grid.Resources> </Grid.Resources>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/>
@@ -11,9 +11,11 @@ namespace mbts.ui.shell {
public class ShellWindowVM : ViewModelBase, IDisposable { public class ShellWindowVM : ViewModelBase, IDisposable {
IShellWindow _model; IShellWindow _model;
UIElement _ui; UIElement _ui;
ShellWindowUI document;
IWindowManager _wm; IWindowManager _wm;
Dispatcher _dispatcher; Dispatcher _dispatcher;
HwndContentHost _hwnd_host; HwndContentHost _hwnd_host;
FloatingWindow _owner;
public ShellWindowVM(IShellWindow model, IWindowManager wm, IShellThreadFactory threads, string host = "") { public ShellWindowVM(IShellWindow model, IWindowManager wm, IShellThreadFactory threads, string host = "") {
Log.assert(model != null); Log.assert(model != null);
@@ -50,6 +52,15 @@ namespace mbts.ui.shell {
public string host_id { get; set; } public string host_id { get; set; }
public Dispatcher Dispatcher { get { return _dispatcher; } } public Dispatcher Dispatcher { get { return _dispatcher; } }
public FloatingWindow owner {
get => _owner;
set {
if (_owner != value) {
_owner = value;
_try_set_unsafe_window();
}
}
}
public string Title { get { return HasCustomTitle? TitleOverride : _model.Title; } } public string Title { get { return HasCustomTitle? TitleOverride : _model.Title; } }
@@ -125,7 +136,6 @@ namespace mbts.ui.shell {
} }
private UIElement create_contents() { private UIElement create_contents() {
ShellWindowUI document = null;
string error_text = null; string error_text = null;
_dispatcher.Invoke(() => { _dispatcher.Invoke(() => {
@@ -166,6 +176,7 @@ namespace mbts.ui.shell {
_dispatcher.Invoke(() => { _dispatcher.Invoke(() => {
var interop_window = new WPFPanel(document.Content); var interop_window = new WPFPanel(document.Content);
retval = new System.Runtime.InteropServices.HandleRef(interop_window, interop_window.Handle); retval = new System.Runtime.InteropServices.HandleRef(interop_window, interop_window.Handle);
//WindowStyle.SetWPFBus(document.Content);
}, DispatcherPriority.Send); }, DispatcherPriority.Send);
_hwnd_host = new HwndContentHost(retval); _hwnd_host = new HwndContentHost(retval);
InitialHeight = _hwnd_host.InitialHeight; InitialHeight = _hwnd_host.InitialHeight;
@@ -206,8 +217,6 @@ namespace mbts.ui.shell {
public bool IsShared { get { return _model is ISharedWindow; } } public bool IsShared { get { return _model is ISharedWindow; } }
public bool HasTabAffinity { get { return _model is ITabAffineWindow; } } public bool HasTabAffinity { get { return _model is ITabAffineWindow; } }
public void Dispose() { public void Dispose() {
_model.TitleChanged -= title_changed; _model.TitleChanged -= title_changed;
_model.IconChanged -= icon_changed; _model.IconChanged -= icon_changed;
@@ -228,5 +237,11 @@ namespace mbts.ui.shell {
Disposable.dispose(ref _hwnd_host); Disposable.dispose(ref _hwnd_host);
} }
void _try_set_unsafe_window() {
if (_owner != null && document?.Content != null) {
document.Content.Dispatcher.InvokeAsync(() =>
WindowStyle.SetUnsafeWindow(document.Content, _owner));
}
}
} }
} }
@@ -11,5 +11,5 @@ namespace mbts.spark {
} }
} }
class PnLRowView : DIYGrid.HighPerformanceRow<PnLSummaryRow, PAndLView.Columns> { } class PnLRowView : DIYGrid.HighPerformanceRow<PnLSummaryRow> { }
} }
@@ -1,9 +1,7 @@
using bts.collections; using bts.collections;
using bts.shell.pnl;
using mbts.ui.controls; using mbts.ui.controls;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
@@ -20,6 +18,7 @@ namespace mbts.ui.spark {
IList<IDisposable> _grid_hooks = new List<IDisposable>(); IList<IDisposable> _grid_hooks = new List<IDisposable>();
IDictionary<DataGridColumn, IDisposable> _column_hooks = new Dictionary<DataGridColumn, IDisposable>(); IDictionary<DataGridColumn, IDisposable> _column_hooks = new Dictionary<DataGridColumn, IDisposable>();
ScrollViewer _scroll_viewer; ScrollViewer _scroll_viewer;
ScrollContentPresenter _scroll_presenter_backing;
IDictionary<object, IDictionary<object, IEnumerable<CellAnimation>>> _row_animation_map = new Dictionary<object, IDictionary<object, IEnumerable<CellAnimation>>>(); IDictionary<object, IDictionary<object, IEnumerable<CellAnimation>>> _row_animation_map = new Dictionary<object, IDictionary<object, IEnumerable<CellAnimation>>>();
IDictionary<TColKey, DIYGrid.ColumnGeometry> _column_layout = new Dictionary<TColKey, DIYGrid.ColumnGeometry>(); IDictionary<TColKey, DIYGrid.ColumnGeometry> _column_layout = new Dictionary<TColKey, DIYGrid.ColumnGeometry>();
@@ -54,14 +53,20 @@ namespace mbts.ui.spark {
} }
} }
ScrollContentPresenter _scroll_presenter =>
_scroll_presenter_backing ?? (_scroll_presenter_backing = _scroll_viewer?.descendants_of_type<ScrollContentPresenter>().FirstOrDefault());
public void Dispose() { public void Dispose() {
_dispose_hooks(); _dispose_hooks();
RemoveRowAnimationChangedHandler(_grid, _grid_RowAnimationChanged); RemoveRowAnimationChangedHandler(_grid, _grid_RowAnimationChanged);
} }
protected override void OnRender(DrawingContext drawingContext) { protected override void OnRender(DrawingContext drawingContext) {
if (_row_animation_map.Count == 0) var sp = _scroll_presenter;
if (sp != null && _row_animation_map.Count == 0)
return; return;
var sp_bounds = new Rect(sp.TranslatePoint(new Point(0, 0), this), sp.RenderSize);
drawingContext.PushClip(new RectangleGeometry(sp_bounds));
foreach (var row_kv in _row_animation_map) { foreach (var row_kv in _row_animation_map) {
if (_rows_presenter.ItemContainerGenerator.ContainerFromItem(row_kv.Key) is FrameworkElement row) { if (_rows_presenter.ItemContainerGenerator.ContainerFromItem(row_kv.Key) is FrameworkElement row) {
if (!row.IsVisible) if (!row.IsVisible)
@@ -69,6 +74,7 @@ namespace mbts.ui.spark {
animate_row(drawingContext, row_kv.Key, row_kv.Value, row); animate_row(drawingContext, row_kv.Key, row_kv.Value, row);
} }
} }
drawingContext.Pop();
} }
protected void animate_row(DrawingContext drawing_context, object row_vm, IDictionary<object, IEnumerable<CellAnimation>> cell_animations, FrameworkElement row_view) { protected void animate_row(DrawingContext drawing_context, object row_vm, IDictionary<object, IEnumerable<CellAnimation>> cell_animations, FrameworkElement row_view) {
@@ -1,8 +1,10 @@
using bts.api; using bts.api;
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace mbts.spark { namespace mbts.spark {
static class SecurityDataHelper { static class SecurityDataHelper {
public static readonly Func<SecurityImmutable, uint> key_fn = s => s.Id;
// Ice // Ice
public static string market_description(this SecurityImmutable security) => security.HasIce ? security.Ice.MarketDescription : string.Empty; public static string market_description(this SecurityImmutable security) => security.HasIce ? security.Ice.MarketDescription : string.Empty;
public static string product_name(this SecurityImmutable security) => security.HasIce ? security.Ice.ProductName : string.Empty; public static string product_name(this SecurityImmutable security) => security.HasIce ? security.Ice.ProductName : string.Empty;
@@ -71,5 +71,17 @@ namespace mbts.spark {
work(); work();
} }
} }
public static IDisposable DoWhile(string name, TimeSpan interval, Func<bool> work, DispatcherPriority priority, double excessive_cycle_ratio = default_excessive_cycle_ratio) {
IDisposable loop = null;
loop = Start(name, interval, priority, impl, excessive_cycle_ratio);
return Disposable.Create(dispose);
void impl() {
if (!work())
Disposable.dispose(ref loop);
}
void dispose() =>
Disposable.dispose(ref loop);
}
} }
} }
@@ -0,0 +1,14 @@
using System.Windows.Data;
namespace mbts.ui {
static class BindingHelper {
public static MultiBinding create_multi(IMultiValueConverter converter, params Binding[] bindings) {
var mb = new MultiBinding {
Converter = converter
};
for (int i = 0; i < bindings.Length; i++)
mb.Bindings.Add(bindings[i]);
return mb;
}
}
}
@@ -0,0 +1,61 @@
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Windows.Media;
namespace mbts.ui {
readonly struct BrushKey : IEquatable<BrushKey> {
readonly int _color;
// Opacity is converted to a ushort, so the 32 hash bits can be split in half: 16 for color, and 16 for opacity.
// This costs some precision wrt opacity; it is doubtful the human eye would be able to discern the difference in any case.
readonly ushort _opacity;
BrushKey(int color, ushort opacity) {
_color = color;
_opacity = opacity;
}
public static BrushKey get(Color color, double opacity = 1.0) {
ExceptionAssert.Argument.Between(opacity, 0.0, 1.0, nameof(opacity));
unchecked {
var opac = (ushort)(opacity * ushort.MaxValue);
// color has a perfect hash (it is 32 bits, so it damn well better).
return new BrushKey(color.GetHashCode(), opac);
}
}
public bool Equals(BrushKey other) =>
_color == other._color &&
_opacity == other._opacity;
public override bool Equals(object obj) =>
obj is BrushKey other && Equals(other);
public override int GetHashCode() =>
// ushort.MaxValue indicates opacity of '1.'
// The value we have is the actual opacity multiplied by 100,000;
// so 1 would actually be a very small opacity: 0.0001.
_opacity == ushort.MaxValue ?
// the last bit indicates if opacity is zero
_color | -1 :
((ushort)_color | (_opacity << 16) | -1) ^ -1;
}
static class FrozenBrushCache {
[ThreadStatic]
static Dictionary<BrushKey, SolidColorBrush> _brushes;
public static SolidColorBrush get_brush(Color color) =>
get_brush(color, 1.0);
public static SolidColorBrush get_brush(Color color, double opacity) {
if (_brushes == null)
_brushes = new Dictionary<BrushKey, SolidColorBrush>();
var key = BrushKey.get(color, opacity);
if (!_brushes.TryGetValue(key, out var brush)) {
_brushes[key] = brush = new SolidColorBrush(color) { Opacity = opacity }.frozen();
}
return brush;
}
}
}
@@ -0,0 +1,59 @@
using bts.utils;
using mbts.ui.dpi;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Windows.Media;
namespace mbts.ui {
readonly struct PenKey : IEquatable<PenKey> {
// This code asserts that thickness will not exceed 100
// this is an arbitrary max that can adjusted if needed
const ushort
_max_thickness = 100,
_thickness_mult = ushort.MaxValue / _max_thickness;
readonly BrushKey _brush_key;
readonly ushort _thickness;
PenKey(BrushKey brush_key, ushort thickness) {
_brush_key = brush_key;
_thickness = thickness;
}
public static PenKey get(BrushKey brush_key, double thickness) {
ExceptionAssert.Argument.Between(thickness, 0, _max_thickness, nameof(thickness));
return new PenKey(brush_key, (ushort)(thickness * _thickness_mult));
}
public bool Equals(PenKey other) =>
_brush_key.Equals(other._brush_key) &&
_thickness == other._thickness;
public override bool Equals(object obj) =>
obj is BrushKey other && Equals(other);
public override int GetHashCode() =>
EqualityComparer.auto_phase(
_brush_key.GetHashCode(),
_thickness.GetHashCode());
}
static class FrozenPenCache {
[ThreadStatic]
static Dictionary<PenKey, Pen> _pens;
public static Pen get_pen(Color color) =>
get_pen(color, HighDpiExtensions.pixel_unit, 1);
public static Pen get_pen(Color color, double thickness, double opacity) {
if (_pens == null)
_pens = new Dictionary<PenKey, Pen>();
var key = PenKey.get(BrushKey.get(color, opacity), thickness);
if (!_pens.TryGetValue(key, out var pen)) {
_pens[key] = pen = new Pen(FrozenBrushCache.get_brush(color, opacity), thickness).frozen();
}
return pen;
}
}
}
+24 -7
View File
@@ -1,4 +1,5 @@
using mbts.ui.dpi; using bts.utils;
using mbts.ui.dpi;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
@@ -72,8 +73,16 @@ namespace mbts.ui.utility.text {
get_glyph_run(text, font_size, 0, 0, available_width, available_height, x_alignment, y_alignment, padding); get_glyph_run(text, font_size, 0, 0, available_width, available_height, x_alignment, y_alignment, padding);
public GlyphRun get_glyph_run( public GlyphRun get_glyph_run(
string text, double font_size, double left, double top, double right, double bottom, string text,
HorizontalAlignment x_alignment, VerticalAlignment y_alignment, Thickness padding) { double font_size,
double left,
double top,
double right,
double bottom,
HorizontalAlignment x_alignment,
VerticalAlignment y_alignment,
Thickness padding,
bool use_layout_rounding = true) {
// //
if (string.IsNullOrEmpty(text)) if (string.IsNullOrEmpty(text))
return null; return null;
@@ -82,6 +91,8 @@ namespace mbts.ui.utility.text {
if (!_try_get_glyph_params(text, font_size, ref glyph_indices, ref advance_widths, out double glyph_width)) if (!_try_get_glyph_params(text, font_size, ref glyph_indices, ref advance_widths, out double glyph_width))
return null; return null;
var origin = _calculate_glyph_run_origin(font_size, left, top, right, bottom, glyph_width, x_alignment, y_alignment, padding); var origin = _calculate_glyph_run_origin(font_size, left, top, right, bottom, glyph_width, x_alignment, y_alignment, padding);
if (use_layout_rounding)
origin = origin.RoundToLayout();
return new GlyphRun(_glyph_typeface, 0, false, font_size, HighDpiExtensions.fdpi_ratio, glyph_indices, origin, advance_widths, null, null, null, null, null, null); return new GlyphRun(_glyph_typeface, 0, false, font_size, HighDpiExtensions.fdpi_ratio, glyph_indices, origin, advance_widths, null, null, null, null, null, null);
} }
@@ -221,7 +232,8 @@ namespace mbts.ui.utility.text {
public bool arrange_glyph_run( public bool arrange_glyph_run(
IReadOnlyList<string> lines, double line_spacing, TextAlignment text_alignment, double font_size, IReadOnlyList<string> lines, double line_spacing, TextAlignment text_alignment, double font_size,
out ushort[] glyph_indices, out double[] advance_widths, out Point[] glyph_offsets, out double glyph_width, out double glyph_height) { out ushort[] glyph_indices, out double[] advance_widths, out Point[] glyph_offsets, out double glyph_width, out double glyph_height,
bool use_layout_rounding = true) {
// //
glyph_width = 0; glyph_width = 0;
glyph_height = 0; glyph_height = 0;
@@ -248,7 +260,8 @@ namespace mbts.ui.utility.text {
new GlyphRun(_glyph_typeface, 0, false, font_size, HighDpiExtensions.fdpi_ratio, indices, origin, advance_widths, offsets, null, null, null, null, null); new GlyphRun(_glyph_typeface, 0, false, font_size, HighDpiExtensions.fdpi_ratio, indices, origin, advance_widths, offsets, null, null, null, null, null);
bool _try_get_glyph_params_left_aligned( bool _try_get_glyph_params_left_aligned(
IReadOnlyList<string> lines, double line_spacing, double font_size, ref ushort[] glyph_indices, ref double[] advance_widths, ref Point[] glyph_offsets, out double glyph_width, out double glyph_height) { IReadOnlyList<string> lines, double line_spacing, double font_size, ref ushort[] glyph_indices, ref double[] advance_widths, ref Point[] glyph_offsets, out double glyph_width, out double glyph_height,
bool use_layout_rounding = true) {
// //
glyph_width = 0; glyph_width = 0;
glyph_height = 0; glyph_height = 0;
@@ -256,9 +269,12 @@ namespace mbts.ui.utility.text {
int n = 0; int n = 0;
foreach (string text in lines) { foreach (string text in lines) {
double line_width = 0; double line_width = 0;
double max_height_mult = 0;
foreach (char c in text) { foreach (char c in text) {
if (!_char_map.TryGetValue(c, out (ushort index, double width) gc)) if (!_char_map.TryGetValue(c, out (ushort index, double width) gc) ||
!_glyph_typeface.AdvanceHeights.TryGetValue(c, out var height_mult))
return false; return false;
MathUtils.exchange_if_gt(ref max_height_mult, height_mult);
glyph_indices[n] = gc.index; glyph_indices[n] = gc.index;
double w = gc.width * font_size; double w = gc.width * font_size;
advance_widths[n] = w; advance_widths[n] = w;
@@ -269,7 +285,8 @@ namespace mbts.ui.utility.text {
x_offset -= line_width; x_offset -= line_width;
if (line_width > glyph_width) if (line_width > glyph_width)
glyph_width = line_width; glyph_width = line_width;
glyph_height += (font_size + line_spacing); glyph_height += (font_size * max_height_mult + line_spacing);
max_height_mult = 0;
} }
glyph_height -= line_spacing; // remove the last line space glyph_height -= line_spacing; // remove the last line space
return true; return true;
@@ -113,7 +113,11 @@ namespace mbts.ui {
bool _arrange_dirty; bool _arrange_dirty;
// fields of public properties // fields of public properties
double _font_size, _line_spacing; double
_font_size,
_content_width_offset,
_content_height_offset,
_line_spacing;
IReadOnlyList<string> _text_lines; IReadOnlyList<string> _text_lines;
GlyphContext _glyph_context; GlyphContext _glyph_context;
GlyphRun _glyph_run; GlyphRun _glyph_run;
@@ -135,6 +139,8 @@ namespace mbts.ui {
public double max_width { get => _vcr.max_width; set => _vcr.max_width = value; } public double max_width { get => _vcr.max_width; set => _vcr.max_width = value; }
public double min_height { get => _vcr.min_height; set => _vcr.min_height = value; } public double min_height { get => _vcr.min_height; set => _vcr.min_height = value; }
public double height { get => _vcr.height; set => _vcr.height = value; } public double height { get => _vcr.height; set => _vcr.height = value; }
public double content_width_offset { get => _content_width_offset; set => _set(ref _content_width_offset, value); }
public double content_height_offset { get => _content_height_offset; set => _set(ref _content_height_offset, value); }
public double max_height { get => _vcr.max_height; set => _vcr.max_height = value; } public double max_height { get => _vcr.max_height; set => _vcr.max_height = value; }
public Size available_size { get => _vcr.available_size; set => _vcr.available_size = value; } public Size available_size { get => _vcr.available_size; set => _vcr.available_size = value; }
public Size layout_size { get { _ensure_current(); return _vcr.layout_size; } } public Size layout_size { get { _ensure_current(); return _vcr.layout_size; } }
@@ -145,6 +151,28 @@ namespace mbts.ui {
return null; return null;
_ensure_current(); _ensure_current();
Point pt = _vcr.content_area.BottomLeft; Point pt = _vcr.content_area.BottomLeft;
if (_content_width_offset != 0) {
switch (horizontal_alignment) {
case HorizontalAlignment.Center:
case HorizontalAlignment.Stretch:
pt.X -= _content_width_offset / 2;
break;
default:
pt.X -= _content_width_offset;
break;
}
}
if (_content_height_offset != 0) {
switch (vertical_alignment) {
case VerticalAlignment.Center:
case VerticalAlignment.Stretch:
pt.Y -= _content_height_offset / 2;
break;
default:
pt.Y -= _content_height_offset;
break;
}
}
if (_glyph_run == null || _glyph_run.BaselineOrigin != pt) if (_glyph_run == null || _glyph_run.BaselineOrigin != pt)
_glyph_run = _glyph_context.from_arranged(_font_size, pt, _glyph_indices, _advance_widths, _glyph_offsets); _glyph_run = _glyph_context.from_arranged(_font_size, pt, _glyph_indices, _advance_widths, _glyph_offsets);
return _glyph_run; return _glyph_run;
@@ -162,12 +190,12 @@ namespace mbts.ui {
void _ensure_current() { void _ensure_current() {
if (_arrange_dirty) { if (_arrange_dirty) {
if (_text_lines.is_null_or_empty()) { if (_text_lines.is_null_or_empty()) {
_vcr.content_width = 0; _vcr.content_width = _content_width_offset;
_vcr.content_height = 0; _vcr.content_height = _content_height_offset;
} else { } else {
_glyph_context.arrange_glyph_run(_text_lines, _line_spacing, TextAlignment.Left, _font_size, out _glyph_indices, out _advance_widths, out _glyph_offsets, out double glyph_width, out double glyph_height); _glyph_context.arrange_glyph_run(_text_lines, _line_spacing, TextAlignment.Left, _font_size, out _glyph_indices, out _advance_widths, out _glyph_offsets, out double glyph_width, out double glyph_height);
_vcr.content_width = glyph_width; _vcr.content_width = glyph_width + _content_width_offset;
_vcr.content_height = glyph_height; _vcr.content_height = glyph_height + _content_height_offset;
} }
_glyph_run = null; _glyph_run = null;
_arrange_dirty = false; _arrange_dirty = false;
@@ -0,0 +1,17 @@
using mbts.utils;
using System.Windows.Input;
namespace mbts.ui.utilities {
static class MouseHelper {
public static MouseButtonState button_state(MouseButton button) {
switch (button) {
case MouseButton.Left: return Mouse.LeftButton;
case MouseButton.Middle: return Mouse.MiddleButton;
case MouseButton.Right: return Mouse.RightButton;
case MouseButton.XButton1: return Mouse.XButton1;
case MouseButton.XButton2: return Mouse.XButton2;
default: throw ExceptionBuilder.Argument.unexpected_case(button, nameof(button));
}
}
}
}
@@ -0,0 +1,44 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;
namespace mbts.ui {
/// <summary>
/// Exposes <see cref="VisualCollection"/> functionality as an <see cref="ICollection{T}"/>.
/// </summary>
class VisualCollectionWrapper : ICollection<Visual> {
readonly VisualCollection _source;
public VisualCollectionWrapper(VisualCollection source) =>
_source = source;
public int Count => _source.Count;
public bool IsReadOnly => _source.IsReadOnly;
public void Add(Visual item) =>
_source.Add(item);
public void Clear() =>
_source.Clear();
public bool Contains(Visual item) =>
_source.Contains(item);
public void CopyTo(Visual[] array, int arrayIndex) =>
_source.CopyTo(array, arrayIndex);
public IEnumerator<Visual> GetEnumerator() =>
_source.Cast<Visual>().GetEnumerator();
public bool Remove(Visual item) {
int old_count = _source.Count;
_source.Remove(item);
return _source.Count != old_count;
}
IEnumerator IEnumerable.GetEnumerator() =>
_source.GetEnumerator();
}
}
@@ -0,0 +1,48 @@
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace mbts.ui {
static class VisualStateHelper {
public static VisualStateGroup create_group(string name, params VisualState[] states) {
var vsg = new VisualStateGroup { Name = name };
for (int i = 0; i < states.Length; i++)
vsg.States.Add(states[i]);
return vsg;
}
public static VisualState create_state(string name, params Timeline[] timelines) {
var sb = new Storyboard();
for (int i = 0; i < timelines.Length; i++)
sb.Children.Add(timelines[i]);
return new VisualState {
Name = name,
Storyboard = sb
};
}
public static ColorAnimation create_color_animation(UIElement target, PropertyPath target_path) {
var timeline = new ColorAnimation {
BeginTime = TimeSpan.Zero,
Duration = TimeSpan.Zero
};
Storyboard.SetTarget(timeline, target);
Storyboard.SetTargetProperty(timeline, target_path);
return timeline;
}
public static ColorAnimation create_color_animation(UIElement target, PropertyPath target_path, Color color) {
var timeline = create_color_animation(target, target_path);
timeline.To = color;
return timeline;
}
public static ColorAnimation create_color_animation(UIElement target, PropertyPath target_path, BindingBase color_binding) {
var timeline = create_color_animation(target, target_path);
BindingOperations.SetBinding(timeline, ColorAnimation.ToProperty, color_binding);
return timeline;
}
}
}
+43 -33
View File
@@ -1,4 +1,5 @@
using bts.utils; using bts.utils;
using mbts.ui.dpi;
using mbts.utils; using mbts.utils;
using System; using System;
using System.Collections; using System.Collections;
@@ -16,6 +17,28 @@ namespace mbts.ui {
static class WPFHelper { static class WPFHelper {
public delegate void PropertyChangedCallback<TValue, TOwner>(TOwner owner, TValue old_value, TValue new_value); public delegate void PropertyChangedCallback<TValue, TOwner>(TOwner owner, TValue old_value, TValue new_value);
public static CoerceValueCallback coerce_value_callback<T>(T fallback = default) =>
(d, base_value) => base_value is T v ? v : fallback;
public static CoerceValueCallback coerce_mutable_freezable<T>(T fallback = default) where T : Freezable {
Func<T> get_fallback;
if (fallback == null) {
get_fallback = () => null;
} else {
fallback.Freeze();
get_fallback = () => (T)fallback.Clone();
}
return coerce_mutable_freezable(get_fallback);
}
public static CoerceValueCallback coerce_mutable_freezable<T>(Func<T> get_fallback) where T : Freezable =>
(d, base_value) => {
var rv = base_value as T ?? get_fallback();
if (rv != null && rv.IsFrozen)
rv = (T)rv.Clone();
return rv;
};
public static DependencyProperty create_dp<TOwner>(string name, Action<TOwner, object> callback, object default_value = null) => public static DependencyProperty create_dp<TOwner>(string name, Action<TOwner, object> callback, object default_value = null) =>
DependencyProperty.Register(name, typeof(object), typeof(TOwner), new PropertyMetadata(default_value, (d, e) => callback(ConvertUtils.try_convert<TOwner>(d), e.NewValue))); DependencyProperty.Register(name, typeof(object), typeof(TOwner), new PropertyMetadata(default_value, (d, e) => callback(ConvertUtils.try_convert<TOwner>(d), e.NewValue)));
@@ -132,33 +155,20 @@ namespace mbts.ui {
} }
}; };
public static void manage_collection_change(DependencyPropertyChangedEventArgs e, NotifyCollectionChangedEventHandler handler) { public static void manage_collection_change(DependencyPropertyChangedEventArgs e, NotifyCollectionChangedEventHandler handler) =>
if (e.OldValue is INotifyCollectionChanged old_ncc) { manage_collection_change(e.OldValue as INotifyCollectionChanged, e.NewValue as INotifyCollectionChanged, handler);
old_ncc.CollectionChanged -= handler;
handler(e.OldValue, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); public static void manage_collection_change(INotifyCollectionChanged old_notifier, INotifyCollectionChanged new_notifier, NotifyCollectionChangedEventHandler handler) {
if (old_notifier != null) {
old_notifier.CollectionChanged -= handler;
handler(old_notifier, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
} }
if (e.NewValue is INotifyCollectionChanged new_ncc) { if (new_notifier != null) {
new_ncc.CollectionChanged += handler; new_notifier.CollectionChanged += handler;
if (e.NewValue is IEnumerable items) if (new_notifier is IEnumerable items) {
foreach (var item in items) foreach (var item in items)
handler(e.NewValue, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); handler(item, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
} }
}
public static void manage_collection_change(DependencyPropertyChangedEventArgs e, NotifyCollectionChangedEventHandler handler, Action<INotifyCollectionChanged> on_old, Action<INotifyCollectionChanged> on_new) =>
manage_collection_change(e.OldValue as INotifyCollectionChanged, e.NewValue as INotifyCollectionChanged, handler, on_old, on_new);
public static void manage_collection_change(INotifyCollectionChanged old_val, INotifyCollectionChanged new_val, NotifyCollectionChangedEventHandler handler) =>
manage_collection_change(old_val, new_val, handler, null, null);
public static void manage_collection_change(INotifyCollectionChanged old_val, INotifyCollectionChanged new_val, NotifyCollectionChangedEventHandler handler, Action<INotifyCollectionChanged> on_old, Action<INotifyCollectionChanged> on_new) {
if (old_val != null) {
old_val.CollectionChanged -= handler;
on_old?.Invoke(old_val);
}
if (new_val != null) {
new_val.CollectionChanged += handler;
on_new?.Invoke(new_val);
} }
} }
@@ -376,7 +386,7 @@ namespace mbts.ui {
switch (x_content_align) { switch (x_content_align) {
case HorizontalAlignment.Left: content_left = border_thickness.Left + padding.Left; break; case HorizontalAlignment.Left: content_left = border_thickness.Left + padding.Left; break;
case HorizontalAlignment.Center: content_left = 0.5 * (result_width - content_width); break; case HorizontalAlignment.Center: content_left = 0.5 * (result_width - content_width); break;
case HorizontalAlignment.Right: content_left = result_width - border_thickness.Right - padding.Right; break; case HorizontalAlignment.Right: content_left = result_width - border_thickness.Right - padding.Right - content_width; break;
default: goto case HorizontalAlignment.Center; default: goto case HorizontalAlignment.Center;
} }
} else { } else {
@@ -408,7 +418,7 @@ namespace mbts.ui {
switch (y_content_align) { switch (y_content_align) {
case VerticalAlignment.Top: content_top = border_thickness.Top + padding.Top; break; case VerticalAlignment.Top: content_top = border_thickness.Top + padding.Top; break;
case VerticalAlignment.Center: content_top = 0.5 * (result_height - content_height); break; case VerticalAlignment.Center: content_top = 0.5 * (result_height - content_height); break;
case VerticalAlignment.Bottom: content_top = result_height - border_thickness.Bottom - padding.Bottom; break; case VerticalAlignment.Bottom: content_top = result_height - border_thickness.Bottom - padding.Bottom - content_height; break;
default: goto case VerticalAlignment.Center; default: goto case VerticalAlignment.Center;
} }
} else { } else {
@@ -434,12 +444,12 @@ namespace mbts.ui {
} }
} }
if (use_layout_rounding) { if (use_layout_rounding) {
content_left = Math.Round(content_left); content_left = content_left.RoundLayoutValue();
content_top = Math.Round(content_top); content_top = content_top.RoundLayoutValue();
content_width = Math.Round(content_width); content_width = content_width.RoundLayoutValue();
content_height = Math.Round(content_height); content_height = content_height.RoundLayoutValue();
result_width = Math.Round(result_width); result_width = result_width.RoundLayoutValue();
result_height = Math.Round(result_height); result_height = result_height.RoundLayoutValue();
} }
content_area = new Rect(content_left, content_top, content_width, content_height); content_area = new Rect(content_left, content_top, content_width, content_height);
resultant_size = new Size(result_width, result_height); resultant_size = new Size(result_width, result_height);
+44 -1
View File
@@ -11,6 +11,15 @@ namespace bts.utils {
public static IComparer<double> error_margin_comparer(double error_margin) => public static IComparer<double> error_margin_comparer(double error_margin) =>
new ErrorMarginComparer.DoubleImpl(error_margin); new ErrorMarginComparer.DoubleImpl(error_margin);
public static T exchange_if_gt<T>(ref T target, T value) where T : struct, IComparable<T> {
if (value.CompareTo(target) > 0) {
var orig = target;
target = value;
return orig;
}
return target;
}
public static bool epsilon_equals(double x, double y) => public static bool epsilon_equals(double x, double y) =>
Math.Abs(x - y) < epsilon; Math.Abs(x - y) < epsilon;
@@ -90,6 +99,12 @@ namespace bts.utils {
return value; return value;
} }
public static byte within_range(byte value, byte min, byte max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
public static int RoundFractionalUnits(double value, double fractional_unit) => public static int RoundFractionalUnits(double value, double fractional_unit) =>
(int)Math.Round(value / fractional_unit); (int)Math.Round(value / fractional_unit);
@@ -128,6 +143,34 @@ namespace bts.utils {
return result < 0 ? result + mod : result; return result < 0 ? result + mod : result;
} }
public static (T min, T max) get_outliers<T>(params T[] values) where T : struct, IComparable<T> {
if (values.Length == 0) {
return (default, default);
}
switch (values.Length) {
case 0: return (default, default);
case 1: return (values[0], values[0]);
default:
T min = values[0], max = values[values.Length - 1];
if (min.CompareTo(max) > 0)
_swap(ref min, ref max);
for (int i = 1; i < values.Length; i++) {
if (min.CompareTo(values[i]) > 0) {
_swap(ref values[i], ref min);
} else if (max.CompareTo(values[i]) < 0) {
_swap(ref values[i], ref max);
}
}
return (min, max);
}
}
static void _swap<T>(ref T a, ref T b) {
var temp = a;
a = b;
b = temp;
}
public static class Primes { public static class Primes {
public const int public const int
P_1087 = 1087, P_1087 = 1087,
@@ -168,4 +211,4 @@ namespace bts.utils {
} }
} }
} }
} }
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more